/**
 * Created by no1 on 2014/9/3.
 */
'use strict';
var session = require('koa-generic-session');
var mysql = require('./mysql.js');
var MUsers = require('../model/users.js');
var MPosts = require('../model/posts.js');
var MTags = require('../model/tags.js');
var md5 = require('md5');
var C = require('../config/index');
var F = require('../common/function');
var uid2 = require('uid2');
var request = require('koa-request');
var _ = require('underscore');
_.str = require('underscore.string');
_.v = require('validator');
var logstash = require('./logFlow/logstash.js');
//var redisCo = F.redisCo;
var imgRule = require('./imgRule');
var logstash = require('./logFlow/logstash.js');
function manLog(loginStatus, API, APIdesc, ip, fields) {
  if (loginStatus['status'] == true) { //是否已登录
    if (_.v.isIn(loginStatus['groupid'], [1, 2, 3])) { //是否管理员组
      delete fields['tokenkey'];
    }
    mysql.query('INSERT INTO mh_manlog(api,apiDesc,uid,nickname,fields,ip,timeline) VALUES(?,?,?,?,?,?,UNIX_TIMESTAMP())',
      [API, APIdesc, loginStatus['uid'], loginStatus['nickname'], JSON.stringify(fields), ip], function () {
      });
  } else {
    mysql.query('INSERT INTO mh_manlog(api,apiDesc,uid,nickname,fields,ip,timeline) VALUES(?,?,?,?,?,?,UNIX_TIMESTAMP())',
      [API, APIdesc, 0, '', JSON.stringify(fields), ip], function () {
      });
  }
}


/**
 @todo API01 创建马甲
 */
exports.addVest = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  var fields = Env.I;
  let loginStatus = fields.loginStatus;
  manLog(loginStatus, 1, '创建马甲', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var mobile = parseInt(fields.mobile);
  var isMobile = F.isMobile(mobile);
  if (!isMobile) {
    return F.returnMsg(400, '手机号码格式不对', 1);
  }
  var isExist = yield F.existMobile(mobile);
  if (isExist) {
    return F.returnMsg(400, '此马甲帐号已存在', 1);
  }

  var password = md5.digest_s(C.vestDefaultPwd).toLowerCase();
  var salt = F.getRandom(6);//随机六位数
  password = md5.digest_s(password + salt);
  var nickName = fields.nickname;
  var regIp = Env.ip;

  var flag = false;
  var newUid = 0;//保存新注册的用户id
  var newUser = yield mysql.query("insert into mh_user(nickname,mobile,password,salt,regtime,regip) values(?,?,?,?,UNIX_TIMESTAMP(),?)", [nickName, mobile, password, salt, regIp]);
  newUid = newUser.insertId;
  if (newUid > 0) {
    mysql.query("insert into mh_user_info(uid) values(?)", [newUid]);
    mysql.query('insert into mh_vest(uid) values(?)', [newUid]);
    flag = true;
  }
  if (flag) {
    return F.returnMsg(200, '添加马甲成功', 3, {uid: newUid});
  } else {
    return F.returnMsg(400, '添加马甲失败', 1);
  }
};

/**
 @todo API02 马甲列表
 */
exports.vest = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 2, '马甲列表', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var act = fields.act;
  var page = fields.page || 1;//当前页
  var pageSize = fields.pageSize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引
  var sql = "SELECT mu.uid,mu.mobile,mu.nickname,mv.`status` FROM mh_vest mv INNER JOIN mh_user mu ON mv.uid=mu.uid ORDER BY vid DESC LIMIT ?,?";
  var vestData = yield mysql.query(sql, [beginIndex, parseInt(pageSize)]);
  if (vestData.length > 0) {
    if (act == 2) {//Web端弹出马甲选择列表
      var userInfo = yield MUsers.getUser('nickname,mobile', 'uid=?', [loginStatus.uid]);
      if (page == 1) {
        vestData.splice(0, 0, {
          'uid': loginStatus.uid,
          'mobile': userInfo[0]['mobile'],
          'nickname': userInfo[0]['nickname'],
          'status': 1
        });
      }
    }
    return F.returnMsg(200, '获取成功', 3, {pageIndex: page, items: vestData});
  }
  return F.returnMsg(300, '获取失败', 1);
};

/**
 @todo API03 修改马甲启用状态
 */
exports.vestStatus = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 3, '修改马甲启用状态', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var uid = fields.uid;
  var status = fields.status;
  if (!(_.v.isIn(status, [0, 1]))) {
    return F.returnMsg(400, '传递的参数错误。', 1);
  }
  var vestData = yield mysql.query('select vid from mh_vest where uid=?', [uid]);
  if (vestData.length > 0) {
    var res = yield mysql.query('update mh_vest set `status`=? where uid=?', [status, uid]);
    if (res.affectedRows > 0) {
      return F.returnMsg(200, '成功', 3, {uid: uid, status: status});
    }
  }
  return F.returnMsg(400, '失败', 3);
};

/**
 @todo API04 马甲发帖统计
 */
exports.vestThread = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 4, '马甲发帖统计', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var sDate = fields.sDate;
  var eDate = fields.eDate;
  var first = fields.first;
  var page = fields.page || 1;//当前页
  var pageSize = fields.pagesize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引
  var condition = " where 1=1 AND mt.`status`=1";
  var sql = "SELECT mvp.uid,mu.mobile,mu.nickname,COUNT(mvp.tid) `count` FROM mh_vest_post mvp LEFT JOIN mh_user mu ON mvp.uid=mu.uid";
  if (first == 1) {//楼主
    sql += " INNER JOIN mh_thread mt ON mvp.pid=mt.pid";
  } else if (first == 0) {
    sql += " LEFT JOIN mh_thread mt ON mvp.tid=mt.tid";
    condition += ' AND mt.uid NOT IN (SELECT uid FROM mh_vest)';
  } else {
    return F.returnMsg(400, '传递的参数错误。', 1);
  }
  var val = [beginIndex, pageSize];
  if (sDate != '' && eDate != '') {
    var startDate = parseInt(new Date(sDate + ' 0:0:0 CST+800').getTime() / 1000);
    var endDate = parseInt(new Date(eDate + ' 0:0:0 CST+800').getTime() / 1000) + 86400;
    condition += ' AND mvp.timeline BETWEEN ? AND ?';
    val = [startDate, endDate, beginIndex, pageSize];
  }
  sql += condition;
  sql += ' GROUP BY mvp.uid LIMIT ?,?';
  var vestPostData = yield mysql.query(sql, val);
  if (vestPostData.length > 0) {
    return F.returnMsg(200, '获取成功', 3, {pageIndex: page, items: vestPostData});
  }
  return F.returnMsg(300, '没有数据', 1);
};

/**
 @todo API05 马甲发帖统计明细
 */
exports.vestThreadDetail = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  manLog(loginStatus, 5, '马甲发帖统计明细', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var sDate = fields.sDate;
  var eDate = fields.eDate;
  var first = fields.first;
  var page = fields.page || 1;//当前页
  var uid = fields.uid;
  var pageSize = fields.pagesize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引
  var condition = " where 1=1 AND mt.`status`=1 AND mp.status=1 AND mvp.uid=?";
  var sql = "SELECT mvp.uid,mvp.tid,mvp.timeline,SUBSTR(mpc.post FROM 1 FOR 20) post,mt.views,mt.liketimes,mt.sharetimes,mt.userreplies as replies,mt.replies-mt.userreplies as vestreplies," +
    "mu.mobile,mu.nickname,mu1.uid vestuid,mu1.nickname vestnickname," +
    "IFNULL((SELECT GROUP_CONCAT(mtt.tagsid) FROM mh_thread_tags mtt INNER JOIN mh_tags mt ON mtt.tagsid=mt.tagid WHERE mtt.tagstype=1 and tid=mvp.tid),'') tagid," +
    "IFNULL((SELECT GROUP_CONCAT(mt.tagtitle) FROM mh_thread_tags mtt INNER JOIN mh_tags mt ON mtt.tagsid=mt.tagid WHERE tid=mvp.tid),'') tagtitle " +
    "FROM mh_vest_post mvp LEFT JOIN mh_post mp ON mvp.pid=mp.pid LEFT JOIN mh_post_content mpc ON mvp.pid=mpc.pid LEFT JOIN mh_user mu ON mvp.uid=mu.uid LEFT JOIN mh_user mu1 ON mp.uid=mu1.uid";
  if (first == 1) {//楼主
    sql += " INNER JOIN mh_thread mt ON mvp.pid=mt.pid";
  } else if (first == 0) {
    sql += " LEFT JOIN mh_thread mt ON mvp.tid=mt.tid";
    condition += ' AND mt.uid NOT IN (SELECT uid FROM mh_vest)';
  } else {
    return F.returnMsg(400, '传递的参数错误。', 1);
  }
  var val = [uid, beginIndex, pageSize];
  if (sDate != '' && eDate != '') {
    var startDate = parseInt(new Date(sDate + ' 0:0:0 CST+800').getTime() / 1000);
    var endDate = parseInt(new Date(eDate + ' 0:0:0 CST+800').getTime() / 1000) + 86400;
    condition += ' AND mvp.timeline BETWEEN ? AND ?';
    val = [uid, startDate, endDate, beginIndex, pageSize];
  }
  sql += condition;
  sql += ' GROUP BY mvp.tid LIMIT ?,?';
  var vestPost = yield mysql.query(sql, val);
  if (vestPost.length > 0) {
    /*
     let tidList=[];
     for(var i in vestPost) {
     tidList.push(vestPost[i].tid);
     }
     let tidListStr = tidList.join();
     let vestP = yield mysql.query('SELECT mp.*,count(mp.uid) as vestreplies FROM mh_post mp RIGHT JOIN mh_vest mv ON mv.uid=mp.uid WHERE mp.tid in ('+tidListStr+') and mp.first=0  GROUP BY mp.tid');
     */

    for (var i in vestPost) {
      vestPost[i]['tags'] = [{}];
      if (vestPost[i]['tagid'] != '') {
        var tempArr = vestPost[i]['tagid'].split(',');
        var tempArr1 = vestPost[i]['tagtitle'].split(',');
        var arr = new Array();
        for (var j in  tempArr) {
          arr[j] = {'tagid': tempArr[j], 'tagtitle': tempArr1[j]};
          if (j > 6) break;
        }
        /*
         for(let v in vestP){
         if(vestP[v].tid==vestPost[i].tid){
         vestPost[i].replies -= vestP[v].vestreplies;
         vestPost[i].vestreplies = vestP[v].vestreplies;
         break;
         }
         }
         */
        vestPost[i]['tags'] = arr;
      }
      delete vestPost[i]['tagid'];
      delete vestPost[i]['tagtitle'];
    }
    return F.returnMsg(200, '成功', 3, {pageIndex: page, items: vestPost});
  }
  return F.returnMsg(300, '没有数据了', 1);
};

/**
 @todo API06 后台主题帖操作
 */
exports.manOperateThread=function*(Env){
  let fields=Env.I;
  let act=fields.act;//1删除普通贴(包含美容日记贴首帖)；2删除整个美容日记贴
  let tid=fields.tid;

  let threadData = yield mysql.queryOne('SELECT mt.tid,mp.pid FROM mh_thread mt inner join mh_post mp on mt.tid=mp.tid WHERE mt.tid=?',[tid]);
  if (!threadData) {
    return F.returnMsg(300, '帖子不存在', 1);
  }

  if(act==1){
    return  yield this.manThread(Env);
  }else if(act==2){
    let status=fields.status;//如果设为有效，将日记帖本身thread表tid跟post表tid对应字段设为有效；若设为无效，将所有日记帖设为无效
    if (status == undefined){
      return F.returnMsg(300, '请传入需要设置的帖子状态', 1);
    }else{
      if(!_.v.isIn(parseInt(status),[0,1,2])){
        return F.returnMsg(300, '帖子状态输入无效', 1);
      }
      status=parseInt(status);
      if(_.v.isIn(status,[0,2])){
        let daily_tid_arr=yield  mysql.query('SELECT tid from mh_thread where (tid=? or fid=?) and status<>? ORDER BY tid ',[tid,tid,status]);
        for(let thread of daily_tid_arr){
          yield this.manThread(Env, {act: 2, tid: thread.tid, tokenkey: fields.tokenkey, apiVerNum: 1, status: status});
        }
        //统一将所有日记帖的DailyNum缓存设为0
        var key = C.redisPre.thread_info;
        var expire = C.redisPre.thread_ttl;
        var tidArr=[];
        let all_daily_tid_arr=yield mysql.query('SELECT tid from mh_thread where tid=? or fid=? ORDER BY tid ',[tid,tid]);
        if(all_daily_tid_arr.length>0){
          for (var i in all_daily_tid_arr) {
            tidArr.push(all_daily_tid_arr[i].tid);
          }
          yield F.redisCo.mhupdatethread(4, key, expire, 0, 'dailyNum', tidArr);
      }
        let returnData = {
          status: status,
          tid:tidArr
        };
        return F.returnMsg(200, '操作成功', 1,returnData);
      }else if(status==1){//设为有效时，将主贴跟主贴内容设为有效
       return yield this.manThread(Env, {act: 2, tid: tid, tokenkey: fields.tokenkey, apiVerNum: 1, status: 1});
      }
    }
  }

};

exports.manThread = function *(Env, data) {
  // 是否内部调用
  let fields;
  var loginStatus = yield F.isLogin(Env);
  manLog(loginStatus, 6, '后台主题帖操作', Env['ip'], Env['I']);
  if (!data) {
    if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
      return F.returnMsg(401, '权限验证失败', 1);
    }
    fields = Env.I;
  } else {
    fields = data;
  }
  var tid = fields.tid;
  var status = fields.status;
  var act=fields.act||1;
  var ctype = fields.ctype;
  var closed = fields.closed;
  var digest = fields.digest;
  var updateFields = "";
  var updateVal = new Array();
  var updateThreadCache = {};
  var threadData = yield mysql.queryOne('SELECT tid,type,pid,uid,fid,status FROM mh_thread WHERE tid=?', [tid]);
  if (!threadData) {
    return F.returnMsg(300, '帖子不存在', 1);
  }
  var previous_status=parseInt(threadData['status']);//之前的帖子状态

  var json = {
    uid: loginStatus.uid,
    tid: tid
  };

  if (status != undefined) {
    status = parseInt(status);
    if (_.v.isIn(status,[0,1,2])) {
      if(status==previous_status){
        return F.returnMsg(300, '状态已生效', 1,{status:status});
      }
      updateFields += "status=?";
      updateVal.splice(updateVal.length, 0, status);

      json.status=status;
      json.action='edit';
    } else {
      return F.returnMsg(400, '传递的参数错误', 1);
    }
    updateThreadCache.status = status;
  }
  if (ctype != undefined) {
    ctype = parseInt(ctype);
    if (_.v.isIn(ctype,[0,1,2])) {
      updateFields += "ctype=?";
      updateVal.splice(updateVal.length, 0, ctype);

      json.ctype=ctype;
      json.action='edit';
    } else {
      return F.returnMsg(400, '传递的参数错误', 1);
    }
    updateThreadCache.ctype = ctype;
  }
  if (closed != undefined) {
    closed = parseInt(closed);
    if (closed == 0 || closed == 1) {
      if (updateFields != '') {
        updateFields += ",closed=?";
      } else {
        updateFields += "closed=?";
      }
      updateVal.splice(updateVal.length, 0, closed);
    } else {
      return F.returnMsg(400, '传递的参数错误', 1);
    }
    updateThreadCache.closed = closed;
  }
  if (digest != undefined) {
    digest = parseInt(digest);
    if (digest == 0 || digest == 1 || digest == 2) {
      if (updateFields != '') {
        updateFields += ",digest=?,digesttimeline=?";
      } else {
        updateFields += "digest=?,digesttimeline=?";
      }
      if (digest == 1) {
        yield F.generateIntegralLog(parseInt(threadData['uid']), 6, tid);//帖子被设为精华后获得积分
      }
      updateVal.splice(updateVal.length, 0, digest);
      updateVal.splice(updateVal.length, 0, F.timestamp());
    } else {
      return F.returnMsg(400, '传递的参数错误', 1);
    }
    updateThreadCache.digest = digest;
    let key = C.redisPre.lists_digest;
    temp = yield F.redisCo.EXISTS(key);
    if (temp == 1) {
      F.redisClient.DEL(key);
    }
  }
  //通知中勤那边修改
  if(json.action=='edit'){
    //更新es数据库
    logstash.article(json);
  }
  if (updateFields != '') {
    var key = '';
    var temp = '';
    updateVal.splice(updateVal.length, 0, tid);
    yield mysql.query("update mh_thread set " + updateFields + ' where tid=?', updateVal);
    yield F.updateThreadCache(parseInt(tid), updateThreadCache);//更新帖子缓存
    if (status != undefined) {
      mysql.query("update mh_post set `status`=? where pid=?", [status, threadData['pid']]);//更新回帖操作
      mysql.query("delete from mh_dynamic_info where tid=?", [tid]);//删除动态信息
      var tagIdArr = [];//帖子标签id数组
      var threadTag = yield mysql.query('SELECT tagsid FROM mh_thread_tags WHERE (tagstype=1 OR tagstype=5 OR tagstype=6) and tid=?', [tid]);//帖子标签
      if (threadTag.length > 0) {
        for (var i in threadTag) {
          tagIdArr.push(threadTag[i].tagsid);
        }
      }
      var favUserArr = [];//收藏帖子用户数组
      var threadFav = yield mysql.query('SELECT uid FROM mh_fav WHERE tid=?', [tid]);
      if (threadFav.length > 0) {
        for (var i in threadFav) {
          favUserArr.push(threadFav[i].uid);
        }
      }
      var likeUserArr = [];//点赞帖子用户数组
      var threadLike = yield mysql.query('SELECT DISTINCT uid FROM mh_likes WHERE tid=? and first=1', [tid]);
      if (threadLike.length > 0) {
        for (var i in threadLike) {
          likeUserArr.push(threadLike[i].uid);
        }
      }
      var postCount = yield mysql.queryOne('SELECT COUNT(pid) count FROM mh_post WHERE tid=?', [tid])//帖子回复数

      if (status == 0 || status==2) {
        if(parseInt(threadData['type'])>0||parseInt(threadData['fid'])>0){
          //如果是美容日记帖首帖，将thread表状态恢复,将缓存所有日记总数-1
          let tidArr = [];
          let daily_tid_arr;
          if(parseInt(threadData['fid'])==0){//如果只是操作日记帖的首帖，将thread表状态恢复，post表状态设为无效(上面已做)
            if(act==1){//act=1,标识只操作主贴的第一天日记（主贴与第一天同为一张帖子）
             yield mysql.query('update mh_thread set `status`=1 where tid=?',[tid]);
              yield F.updateThreadCache(parseInt(tid), {status:1});//更新帖子缓存
              json = {
                uid: loginStatus.uid,
                tid: tid,
                status:1
              };
              logstash.article(json);
            }
          }
          //如果是从有效状态变为无效或者不显示状态
          if (previous_status == 1) {
            mysql.query('update mh_thread_extend set dailyNum=dailyNum-1 where tid=?', [parseInt(threadData['type']) > 0 ? tid : parseInt(threadData['fid'])]);
            //将涉及到的所有日记的 dailyNum-1
            if (act == 1) {//如果只无效单一日记帖，将相关日记贴dailyNum-1
              let daily_fid = parseInt(threadData['type']) > 0 ? tid : parseInt(threadData['fid']);
              daily_tid_arr = yield  mysql.query('SELECT tid from mh_thread where tid=? or fid=? ORDER BY tid ', [daily_fid, daily_fid]);
              if (daily_tid_arr.length > 0) {
                for (var i in daily_tid_arr) {
                  tidArr.push(daily_tid_arr[i].tid);
                  json = {
                    uid: loginStatus.uid,
                    tid: tid,
                    status:1
                  };
                  logstash.article(json);
                }
                var key = C.redisPre.thread_info;
                var expire = C.redisPre.thread_ttl;
                yield F.redisCo.mhincreasethreadfield(4, key, expire, -1, 'dailyNum', tidArr);
              }
            }
          }
        }

        //如果是从有效状态变为无效或者不显示状态
        if (previous_status == 1) {
          if (tagIdArr.length > 0) {
            mysql.query("UPDATE mh_tags set tagcount=tagcount-1 WHERE tagid in(" + tagIdArr.join(',') + ")");//更新帖子标签的帖子数
            for (var i in tagIdArr) {
              //更新标签信息开始
              key = C.redisPre.tag_info;
              key = _.str.sprintf(key, parseInt(tagIdArr[i]), 1);
              temp = yield F.redisCo.EXISTS(key);
              if (temp == 1) {
                F.redisClient.HINCRBY(key, 'tagcount', -1);//标签使用次数-1
              }
              //更新标签信息结束
            }
          }
          if (favUserArr.length > 0) {
            mysql.query("UPDATE mh_user_info set tfavtimes=tfavtimes-1 WHERE uid in(" + favUserArr.join(',') + ")");//更新帖子收藏人的收藏帖子数
            for (var i in favUserArr) {
              //更新收藏人信息开始
              key = C.redisPre.user_info;
              key = _.str.sprintf(key, parseInt(favUserArr[i]));
              temp = yield F.redisCo.EXISTS(key);
              if (temp == 1) {
                F.redisClient.HINCRBY(key, 'tfavtimes', -1);//收藏用户收藏数-1
              }
              //更新收藏人信息结束
            }
          }
          let updateDailySQL = ' ';
          //如果是美容日记帖，将美容日记统计字段也-1
          if (act == 2 && threadData['fid'] == 0 && threadData['type'] > 0) {
            updateDailySQL = 'plasticthreads=plasticthreads-1, ';
          }
          mysql.query("UPDATE mh_user_info set threads=threads-1," + updateDailySQL + "posts=posts-1,beliked=beliked-" + likeUserArr.length + " WHERE uid=?", [threadData['uid']]);//更新发帖人的发帖数，回帖数
          //更新发帖人信息开始
          key = C.redisPre.user_info;
          key = _.str.sprintf(key, parseInt(threadData['uid']));
          temp = yield F.redisCo.EXISTS(key);
          if (temp == 1) {
            F.redisClient.HINCRBY(key, 'threads', -1);//发帖人发帖数-1
            F.redisClient.HINCRBY(key, 'posts', -1);//发帖人回帖数-1
            if (act == 2 && threadData['fid'] == 0 && threadData['type'] > 0) {//美容标题帖
              F.redisClient.HINCRBY(key, 'plasticthreads', -1);//发帖人发帖数-1
            }
          }
          //更新发帖人信息结束

          //更新帖子的投诉为已处理开始
          mysql.query('UPDATE mh_post_complain SET `status`=1 WHERE tid=?', [tid]);
          //更新帖子的投诉为已处理结束

          yield F.generateIntegralLog(parseInt(threadData['uid']), 5, tid);//帖子被管理员删除后扣积分
        }
      } else {//设为有效的情况
            if(parseInt(threadData['type'])>0||parseInt(threadData['fid'])>0){
              let daily_fid=parseInt(threadData['type'])>0?tid:parseInt(threadData['fid']);
              let tidArr=[];
              let daily_tid_arr=yield  mysql.query('SELECT tid from mh_thread where tid=? or fid=? ORDER BY tid ',[daily_fid,daily_fid]);
              if(daily_tid_arr.length>0){
                for (var i in daily_tid_arr) {
                  tidArr.push(daily_tid_arr[i].tid);
                }
                var key = C.redisPre.thread_info;
                var expire = C.redisPre.thread_ttl;
                if(act==2){
                  yield F.redisCo.mhupdatethread(4, key, expire, 1, 'dailyNum', tidArr);//批量修改缓存日记帖子总数
                }else{
                  yield F.redisCo.mhincreasethreadfield(4, key, expire, 1, 'dailyNum', tidArr);//如果是美容日记帖首帖,将日记总数+1
                }
              }

              if(act==2){//如果是激活整个美容日记帖，将日记总帖数设为1,否则只作+1处理
                mysql.query('update mh_thread_extend set dailyNum=1 where tid=?', [tid]);
              } else {
                mysql.query('update mh_thread_extend set dailyNum=dailyNum+1 where tid=?', [parseInt(threadData['type']) > 0 ? tid : parseInt(threadData['fid'])]);
              }
            }
        if (tagIdArr.length > 0) {
          mysql.query("UPDATE mh_tags set tagcount=tagcount+1 WHERE tagid in(" + tagIdArr.join(',') + ")");//更新帖子标签的帖子数
          for (var i in tagIdArr) {
            //更新标签信息开始
            key = C.redisPre.tag_info;
            key = _.str.sprintf(key, parseInt(tagIdArr[i]), 1);
            temp = yield F.redisCo.EXISTS(key);
            if (temp == 1) {
              F.redisClient.HINCRBY(key, 'tagcount', 1);//标签使用次数+1
            }
            //更新标签信息结束
          }
        }
        if (favUserArr.length > 0) {
          mysql.query("UPDATE mh_user_info set tfavtimes=tfavtimes+1 WHERE uid in(" + favUserArr.join(',') + ")");//更新帖子收藏人的收藏帖子数
          for (var i in favUserArr) {
            //更新收藏人信息开始
            key = C.redisPre.user_info;
            key = _.str.sprintf(key, parseInt(favUserArr[i]));
            temp = yield F.redisCo.EXISTS(key);
            if (temp == 1) {
              F.redisClient.HINCRBY(key, 'tfavtimes', 1);//收藏用户收藏数+1
            }
            //更新收藏人信息结束
          }
        }
        //更新发帖人信息开始
        let updateDailySQL = ' ';
        //如果是美容日记帖，将美容日记统计字段也+1
        if (act == 2 && threadData['fid'] == 0 && threadData['type'] > 0) {
          updateDailySQL = 'plasticthreads=plasticthreads+1, ';
        }
        key = C.redisPre.user_info;
        key = _.str.sprintf(key, parseInt(threadData['uid']));
        temp = yield F.redisCo.EXISTS(key);
        if (temp == 1) {
          F.redisClient.HINCRBY(key, 'threads', 1);//用户发帖数+1
          F.redisClient.HINCRBY(key, 'posts', 1);//用户回帖数+1
          if (act == 2 && threadData['fid'] == 0 && threadData['type'] > 0) {//整形帖
            F.redisClient.HINCRBY(key, 'plasticthreads', 1);//用户发整形帖数+1
          }
        }
        mysql.query("UPDATE mh_user_info set threads=threads+1,"+updateDailySQL+" posts=posts+1,beliked=beliked+" + likeUserArr.length + " WHERE uid=?", [threadData['uid']]);//更新发帖人的发帖数，回帖数
        //更新发帖人信息结束
      }

      //重新写最新帖子缓存开始
      key = C.redisPre.lists_news;
      key = _.str.sprintf(key, 0);
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.DEL(key);
        yield F.newestThreadListCache();
      }
      //重新写最新帖子缓存结束

      //重新写发帖人发帖缓存开始
      key = C.redisPre.lists_user;
      key = _.str.sprintf(key, parseInt(threadData['uid']));
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.DEL(key);
        yield F.usersThreadCache([parseInt(threadData['uid'])]);
      }
      //重新写发帖人发帖缓存结束
    }
    if (digest != undefined) {//设为精华帖时，更新发帖人的精华帖数缓存
      key = C.redisPre.user_info;
      key = _.str.sprintf(key, parseInt(threadData['uid']));
      temp = yield F.redisCo.EXISTS(key);
      if (digest == 1) {
        mysql.query("UPDATE mh_user_info set digestthreads=digestthreads+1 WHERE uid=?", [threadData['uid']]);//更新发帖人的精华帖数
        //更新发帖人信息开始
        if (temp == 1) {
          F.redisClient.HINCRBY(key, 'digestthreads', 1);//用户发帖数+1
        }
        //更新发帖人信息结束
      } else {
        mysql.query("UPDATE mh_user_info set digestthreads=digestthreads-1 WHERE uid=?", [threadData['uid']]);//更新发帖人的精华帖数
        //更新发帖人信息开始
        if (temp == 1) {
          F.redisClient.HINCRBY(key, 'digestthreads', -1);//用户发帖数+1
        }
        //更新发帖人信息结束
      }
    }
  }
  var result = yield mysql.queryOne('select closed,status,digest,ctype from mh_thread where tid=?', [tid]);
  var returnData = {
    closed: result['closed'],
    status: result['status'],
    digest: result['digest'],
    ctype: result['ctype'],
    tid:[tid]
  };
  if (!data||(act==2&&status==1)) {//排除将整个美容日记帖设为有效的情况
    return F.returnMsg(200, '成功', 3, returnData);
  }

};

/**
 @todo API07 后台回复帖操作
 */
exports.manPost = function *(Env, data) {
  // 是否内部调用
  let fields;
  var loginStatus = yield F.isLogin(Env);
  manLog(loginStatus, 7, '后台回复帖操作', Env['ip'], Env['I']);
  if (!data) {
    if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
      return F.returnMsg(401, '权限验证失败', {status:status});
    }
    fields = Env.I;
  } else {
    fields = data;
  }

  var pid = fields.pid;
  var postData = yield mysql.query('SELECT tid,uid,vest,status FROM mh_post WHERE pid=?', [pid]);
  if (postData.length == 0) {
    return F.returnMsg(400, '此回帖不存在', 1);
  }
  var previous_status=parseInt(postData[0]['status']);

  let is_user = postData[0]['vest'] == 0 ? 1 : 0;
  var threadData = yield mysql.query('SELECT tid FROM mh_thread WHERE pid=?', [pid]);
  if (threadData.length > 0) {
    return F.returnMsg(400, '禁止操作', 1);
  }
  var status = parseInt(fields.status);
  if (!_.v.isIn(status,[0,1,2])){
    return F.returnMsg(400, '传递的参数错误', 1);
  }else{
    if(status==previous_status){
      return F.returnMsg(300, '状态已生效', 1,{status:status});
    }
  }
  var affRow = yield mysql.query('update mh_post set `status`=? where pid=?', [status, pid]);
  if (affRow.affectedRows > 0) {
    var key = C.redisPre.thread_info;
    key = _.str.sprintf(key, parseInt(postData[0]['tid']));
    var temp = yield F.redisCo.EXISTS(key);
    if (status == 0 || status == 2) {//设为无效时主题帖回复数-1
      mysql.query('UPDATE mh_thread SET replies=replies-1,userreplies=userreplies-? WHERE tid=?', [is_user, postData[0]['tid']]);//
      //更新帖子信息开始
      if(previous_status==1){//从有效回帖更新为无效回帖的情况
        if (temp == 1) {
          //更新帖子的最近三个回帖开始
          var postUsers = JSON.stringify([]);
          var postUserseData = yield MPosts.getPostUsers({"tid": parseInt(postData[0]['tid'])});
          if (postUserseData.length > 0) {
            postUsers = JSON.stringify(postUserseData);
          }
          var updateThreadCache = {};
          updateThreadCache.postusers = postUsers;
          yield F.updateThreadCache(parseInt(postData[0]['tid']), updateThreadCache);//更新帖子缓存
          //更新帖子的最近三个回帖结束
          F.redisClient.HINCRBY(key, 'replies', -1);//帖子回复数-1
        }
        //更新帖子信息结束
        //更新帖子的投诉为已处理开始
        mysql.query('UPDATE mh_post_complain SET `status`=1 WHERE pid=?', [pid]);
        //更新帖子的投诉为已处理结束
        mysql.query("delete from mh_dynamic_info where pid=?", [pid]);//删除动态信息
        yield F.generateIntegralLog(parseInt(postData[0]['uid']), 17, pid);//回帖被管理员删除后扣积分
      }
    } else {//设为有效时主题帖回复数+1
      mysql.query('UPDATE mh_thread SET replies=replies+1,userreplies=userreplies+? WHERE tid=?', [is_user, postData[0]['tid']]);
      if (temp == 1) {
        F.redisClient.HINCRBY(key, 'replies', 1);//帖子回复数+1
      }
    }
    if (!data) {
      return F.returnMsg(200, '成功', 3);
    }
  }
};

/**
 @todo API08 切换马甲
 */
exports.changeVest = function *(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 8, '切换马甲', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  //var fields = Env.I;
  var vestUid = fields.vestuid;
  var vestNickname = fields.vestnickname;
  F.redisClient.hmset('siss:user:uid_' + loginStatus.uid,
    'uid', loginStatus.uid,
    'groupid', loginStatus.groupid,
    'nickname', loginStatus.nickname,
    'vestuid', vestUid,
    'vestnickname', vestNickname
  );
  return F.returnMsg(200, '切换成功', 3, {vestuid: vestUid, vestnickname: vestNickname});
};

/**
 @todo API09 用户列表
 */
exports.users = function *(Env) {
  var loginStatus = yield F.isLogin(Env);
  manLog(loginStatus, 9, '用户列表', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var fields = Env.I;
  var page = fields.page || 1;
  var pageSize = fields.pagesize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;

  var findFields = [];
  var findVal = [];

  if (fields.uid) {
    findFields.push('u.uid=?');
    findVal.push(fields.uid);
  }

  if (fields.mobile) {
    findFields.push('u.mobile = ?');
    findVal.push(fields.mobile);
  }

  if (fields.nickname) {
    findFields.push('u.nickname REGEXP ?');
    findVal.push(fields.nickname);
  }

  if (fields.groupid) {
    findFields.push('u.groupid = ?');
    findVal.push(fields.groupid);
  }
  if (fields.ip) {
    findFields.push('u.regip REGEXP ?');
    findVal.push(fields.ip);
  }

  if (fields.channelid) {
    findFields.push('ui.channelid = ?');
    findVal.push(fields.channelid);
  }

  if (fields.sDate && fields.eDate) {
    var sDate = parseInt(new Date(fields.sDate + ' 0:0:0 CST+800').getTime() / 1000);
    var eDate = parseInt(new Date(fields.eDate + ' 0:0:0 CST+800').getTime() / 1000) + 86400;
    findFields.push('u.regtime>=? AND u.regtime<?');
    findVal.push(sDate);
    findVal.push(eDate);
  }
  if (fields.talentid) {
    findFields.push('ui.talentid = ?');
    findVal.push(fields.talentid);
  }
  findFields.push('1=1');
  findVal.push(beginIndex);
  findVal.push(parseInt(pageSize));
  var data = yield mysql.query('SELECT ' +
    'u.uid,IFNULL(u.nickname,"") nickname,ui.name,u.regtime,IFNULL(u.mobile,"") mobile,u.groupid,g.grouptitle,ui.channelid,ui.threads,(ui.posts-ui.threads) posts,ui.friends,ui.fans,ui.tfavtimes,ui.pintagtimes,u.mediatype,ui.integral,ui.talentid ' +
    'FROM mh_user u LEFT JOIN mh_user_info ui ON u.uid=ui.uid ' +
    'LEFT JOIN mh_group g ON u.groupid = g.groupid ' +
    'WHERE ' + findFields.join(' AND ') + ' ' +
    'ORDER BY u.uid DESC ' +
    'LIMIT ?,?', findVal);
  if (data) {
    for (var i in data) {
      if (data[i].mobile != '') {
        data[i].mobile = data[i].mobile.toString().substr(0, 4) + '***' + data[i].mobile.toString().substr(7, 4);
      }
      data[i].talentname = '';
      if (data[i].talentid > 0) {
        data[i].talentname = F.getTalentInfo(data[i].talentid).name;
      }
    }
    return F.returnMsg(200, '成功', 3, {pageIndex: page, items: data});
  } else {
    return F.returnMsg(300, '无数据', 1, {pageIndex: page, items: []});
  }
};

/**
 @todo API10 修改帖子内容
 */
exports.postEdit = function*(Env) {
  var loginStatus = yield F.isLogin(Env);
  manLog(loginStatus, 10, '修改帖子内容', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var pid = 0;
  var tid = 0;
  var fields = Env.I;
  var imgback = fields.imgback == undefined ? -1 : parseInt(fields.imgback);
  var postCon = fields.postCon || '';
  var minLen = 0;//发帖内容最短长度
  if (imgback == 0) {//无图
    minLen = 5;
  }

  if (!_.v.isLength(postCon, minLen, 1000)) {
    return F.returnMsg(400, '贴子内容必须在' + minLen + '至1000个字符以内', 1);
  }

  if (fields.tid) {
    var imgDesc = fields.imgdesc || '';
    var video = fields.video;
    var threadData = yield mysql.queryOne("SELECT pid,type,imgcount,validimg FROM mh_thread WHERE tid=?", [fields.tid]);
    //var imgcount = fields.imgcount || 0;//图片数量 最少一个图片
    var imgcount = threadData['imgcount'];
    imgcount = parseInt(imgcount);
    //if (!(_.v.isIn(imgback, [-1,1,2,3]))) {
    //  return F.returnMsg(400,'传递的参数错误',1);
    //}
    //修改主题帖时必须传最少一个标签
    /*2015.08.21取消强制加标签限制
    if (tags == undefined || tags == '') {
      return F.returnMsg(400, '必须有一个标签且最多只能6个标签', 1);
    }*/
    var tags = fields.tags;
    tags = JSON.parse(tags);
    /*2015.08.21取消强制加标签限制
    if (!Array.isArray(tags)) {
      return F.returnMsg(400, '必须有一个标签且最多只能6个标签', 1);
    }*/

    //修改帖子视频时，关键字必须是13到30位之间
    if (!_.v.isLength(video, 0)) {
      if (!_.v.isLength(video, 13, 30)) {
        return F.returnMsg(400, '视频关键字必须在13到30字内', 1);
      }
    }
    var len = tags.length;//传过来的所有标签
    var tagLen = 0;//作为标签的长度
    //var itemCount = 0;//作为项目的长度
    var brondTagid = yield F.getBrondTagid();//话题下的标签id
    var lardTagid = C.lard_tagid;//随便聊聊标签id
    var flag = false;//是否强制加入随便聊聊标签
    var tempTagidArr = [];
    for (var i = len - 1; i >= 0; i--) {
      if (!_.v.isInt(tags[i].tagsid) || !_.isString(tags[i].tagstitle)) {//标签id必须是整形，可为0、内容必须为字符串
        continue;
      }
      if (tags[i].tagsid > 0) {
        tempTagidArr.push(tags[i].tagsid);
      }
      if (tags[i].tagsType != 6 && imgcount > 0) {
        if (!_.v.isInt(tags[i].x) || !_.v.isInt(tags[i].y) || !_.v.isInt(tags[i].imgindex)) {
          continue;
        }
      }
      var imgIndex = tags[i].imgindex || 0;//标签所在图的索引
      //if(imgIndex==undefined){
      //  return F.returnMsg(400, '没有指定某个标签在哪个图', 1);
      //}
      if (tags[i].tagsid == 0 && tags[i].tagstitle.length > 30) {
        return F.returnMsg(400, '标签长度不能大于30个字符', 1);
      }
      if (tags[i].tagstitle == '' && tags[i].tagsid == 0) {
        tags.splice(i, 1);
      }/*2015.08.21不强制加标签
      else {
        if (tags[i].tagsType == 6 && tags[i].tagsid != 0) {//作为项目的标签
          itemCount += 1;
        } else {
          if (parseInt(imgIndex) == 0) {//目前第一张图才强制加标签
            tagLen += 1;
          }
        }
      }*/
    }
    //if(type==1&&itemCount==0){//美容日志帖
    //  return F.returnMsg(400, '项目必须有一个', 1);
    //}
    if (tagLen > 6) {
      return F.returnMsg(400, '最多只能6个标签', 1);
    }
    flag = _.v.isIn(lardTagid, tempTagidArr);
    if (_.isEmpty(_.intersection(tempTagidArr, brondTagid)) && !flag) {
      tags.push({"tagsType": 99, "tagsid": lardTagid, "tagstitle": "", "x": 0, "y": 0});
    }
    //验证图片描述json串开始
    if (imgDesc != '') {
      var imgDescLen = imgDesc.length;
      if (imgDescLen > 2045) {//数据表字段类型varchar，长度2048
        return F.returnMsg(400, '图片描述内容太长', 1);
      }
      var tmpImgDesc = F.isJson(imgDesc);
      if (tmpImgDesc) {
        if (tmpImgDesc.desc != undefined) {
          var tmpArr = tmpImgDesc.desc;
          if (!Array.isArray(tmpArr)) {
            return F.returnMsg(400, '参数有误,请检查', 1);
          }
          for (var i in tmpArr) {
            if (!_.isString(tmpArr[i])) {
              return F.returnMsg(400, '参数有误,请检查', 1);
            }
          }
        } else {
          return F.returnMsg(400, '参数有误,请检查', 1);
        }
      } else {
        return F.returnMsg(400, '参数有误,请检查', 1);
      }
    }
    //验证图片描述json串结束

    if (threadData) {
      pid = threadData['pid'];
      tid = fields.tid;
    }
  } else if (fields.pid) {
    pid = fields.pid;
    var postData = yield mysql.queryOne('SELECT tid FROM mh_post WHERE pid=?', [pid]);
    tid = postData['tid'];
  }
  var setField = [];
  var setVal = [];
  setField.push('`post`=?');
  setVal.push(postCon);
  if (imgDesc != undefined) {
    setField.push('imgdesc=?');
    setVal.push(imgDesc);
  }
  setVal.push(pid);
  var affRow = yield mysql.query('update mh_post_content set ' + setField.toString() + ' where pid=?', setVal);
  if (affRow.affectedRows > 0) {

    // logstash 流程
    var json = {
      uid: loginStatus.uid,
      tid: tid,
      action: 'edit',
      articleContent: postCon
    };
    logstash.article(json);


    if (fields.tid) {//修改主题帖时，修改图片、标签
      var imgStatus = fields.imgstatus;//设置图片状态
      if (imgStatus) {
        imgStatus = JSON.parse(imgStatus);
        var validimgArr = threadData['validimg'].split(',');
        for (var j in imgStatus) {
          for (var k in validimgArr) {
            var temp = validimgArr[k].split('-');
            if (imgStatus[j].imgindex == temp[0]) {
              validimgArr[k] = temp[0] + '-' + imgStatus[j].status;
            }
          }
        }
        mysql.query('UPDATE mh_thread SET validimg=? WHERE tid=?', [validimgArr.toString(), parseInt(fields.tid)]);
      }
      var imgext = '';
      switch (imgback) {
        case 1:
          imgext = 'jpg';
          break;
        case 2:
          imgext = 'gif';
          break;
        case 3:
          imgext = 'png';
          break;
      }
      if (imgback >= 0) {
        mysql.query('update mh_post set `imgext`=? where pid=?', [imgext, pid]);
      }

      //先执行删除、更新标签使用次数
      var affRow = yield mysql.query('delete from mh_thread_tags where tid=? and tagstype <>6', [fields.tid]);
      if (affRow.affectedRows > 0) {
        var tagsData = yield mysql.queryOne('select GROUP_CONCAT(tagsid) as tags from mh_thread_tags where tid=? and tagstype <>6', [fields.tid]);
        if (tagsData && tagsData['tags']) {
          var tagArray = tagsData['tags'].split(',');
          for (var i in tagArray) {
            mysql.query('update mh_tags set tagcount=tagcount-1 where tagid=?', [tagArray[i]]);
          }
        }
      }
      // 记录标签
      for (var l in tags) {
        var tagData = tags[l];
        var tagsType = tagData.tagsType;
        var tagsid = tagData.tagsid;
        var tagstitle = tagData.tagstitle;
        var x = tagData.x || 0;
        var y = tagData.y || 0;

        var placeLeft = tagData.x > 50 ? 1 : 0;
        if (_.v.isIn(tagData.placeLeft, [0, 1])) {
          placeLeft = tagData.placeLeft;
        }

        var imgIndex = tagData.imgindex != undefined ? parseInt(tagData.imgindex) : 0;//版本3之前没多图,故不用传标签的图索引
        var poiid = '';
        switch (tagsType) {
          case 1://传统标签
          case 4://lbs标签
          case 5://传统标签中的水印标签
          case 6://美容标签
          case 99://随便聊聊标签
            if (tagsid == 0) {//没传标签id过来
              if (tagstitle == '') {
                continue;
              }
              var tagData = yield mysql.query('SELECT tagid FROM mh_tags WHERE tagtitle=?', [tagstitle]);
              if (tagData.length > 0) {//已经存在标签
                tagsid = tagData[0].tagid;
              } else {
                var retTag = yield mysql.query('INSERT INTO mh_tags(tagtype,tagtitle,uid) VALUES(?,?,?)', [2, tagstitle, parseInt(loginStatus.uid)]);//2 为用户自定义标签
                tagsid = retTag.insertId;
              }
            } else {//有传标签id过来
              var addWhere = '';
              if (tagsType == 6) {//美容标签类型
                addWhere += ' AND tagtype=4'
              }
              var tTag = yield mysql.query('SELECT tagid,tagtitle FROM mh_tags WHERE tagid=?' + addWhere, [tagsid]);
              if (tTag.length > 0) {
                tagstitle = tTag[0].tagtitle;
              } else {
                continue;
              }
            }
            if (tagsType == 4 && tagData.poiid) {//lbs标签
              //写poi详细开始
              poiid = tagData.poiid;
              var poiDetail = yield mysql.query('SELECT version,poiid,pcode,pname,citycode,cityname,adcode,adname,address,`name`,longitude,latitude FROM mh_poi_detail WHERE version=? AND poiid=?', [C.amap.api_ver, poiid]);
              if (poiDetail.length == 0) {
                F.AMAPSearchPoi([poiid],
                  function (jsonData, pois) {
                    var poisArr = jsonData.pois;
                    mysql.query('insert into mh_poi_detail(version,poiid,pcode,pname,citycode,cityname,adcode,adname,address,`name`,longitude,latitude,poidetail,lasttid,tagid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [C.amap.api_ver, pois.id, pois.pcode, pois.pname, pois.citycode, pois.cityname, pois.adcode, pois.adname, pois.address, pois.name, pois.longitude, pois.latitude, JSON.stringify(poisArr), tid, tagsid]);
                    F.savePoi2Mongo({
                      poiid: pois.id,
                      name: pois.name,
                      tagid: tagsid,
                      longitude: pois.longitude,
                      latitude: pois.latitude
                    });
                  }
                );
              }
              //写poi详细结束
            }
            break;
          case 2://用户
            break;
          case 3://帖子
            break;
        }
        mysql.query('INSERT INTO mh_thread_tags(tid,tagsid,tagstype,tagstitle,x,y,imgindex,poiid,placeLeft) VALUES(?,?,?,?,?,?,?,?,?)', [tid, tagsid, tagsType, tagstitle, x, y, imgIndex, poiid, placeLeft]);
        if (tagsType == 1 || tagsType == 4 || tagsType == 5 || tagsType == 6) {//传统标签、水印标签、美容标签时写入最后一个发帖，更新热度
          mysql.query('UPDATE mh_tags SET lasttid=? WHERE tagid=?', [tid, tagsid]);
          mysql.query('UPDATE mh_tags SET tagcount=tagcount+1 WHERE tagid=?', [tagsid]);//更新标签热度
        }
      }
      //如果有传入视频关键字，则更新
      if (_.v.isLength(video, 13, 30)) {
        mysql.query('UPDATE mh_thread SET video=? WHERE tid=?', [video, fields.tid]);//更新视频关键字
      }
    }
    var returnData = {};
    if (fields.tid) {
      if (imgback == -1 || imgback == 0) {

      } else {
        // 又拍云参数
        var crop = fields.crop;
        var signArr = [];
        let imageStringArr = [];
        for (var i = 0; i < imgcount; i++) {
          /*
           var upyun = {
           type: 2,
           pid: pid,
           imgBack: imgback,
           imgindex: i//图片索引
           };
           if (crop) {
           upyun['crop'] = crop;
           }
           signArr[i] = yield F.getUpyunSign(upyun);
           */
          let imgBack = '';
          switch (imgback) {
            case '1':
              imgBack = 'jpg';
              break;
            case '2':
              imgBack = 'gif';
              break;
            case '3':
              imgBack = 'png';
              break;
            default :
              imgBack = 'jpg'
          }
          let imgStr = imgRule.id2imgStr('p', pid, imgBack);
          imageStringArr.push(imgStr);
          let urlArr = imgRule.str2imgURI(imgStr);
          let upyun = urlArr[0];
          if (crop) upyun.crop = crop;
          signArr[i] = yield F.getUpyunSignB(upyun);
          signArr[i].imgstr = imgStr;
        }
        returnData.upYunSign = signArr;
        ////临时使用
        //let tmp = imageStringArr.toString();
        //mysql.query('UPDATE mh_thread SET imagestring=? WHERE tid=?', [tmp, fields.tid]);//修改数据库中的图
      }
      if (_.v.isLength(video, 13, 30)) {
        /*
         var videoimgSign = {
         type: 2,
         pid: pid,
         imgBack: imgback,
         imgindex: 'video'//图片索引或者是视频截图标记
         };
         returnData.videoimgSign = yield F.getUpyunSign(videoimgSign);
         */
        let imgStr = imgRule.id2imgStr('p', pid, imgback, 'video');
        let urlArr = imgRule.str2imgURI(imgStr);
        let upyun = urlArr[0];
        returnData.videoimgSign = yield F.getUpyunSignB(upyun);
      }
    }
    //删除主题帖缓存
    var key = C.redisPre.thread_info;
    key = _.str.sprintf(key, parseInt(tid));
    var temp = yield F.redisCo.EXISTS(key);
    if (temp == 1) {
      F.redisClient.DEL(key);
    }
    returnData.pid = pid;
    return F.returnMsg(200, '成功', 3, returnData);
  }
};

/**
 @todo API11  主题帖修改标签
 */
exports.threadTags = function*(Env) {
//  var loginStatus = yield F.isLogin(Env);
//  if(!(loginStatus.status==true&&F.isManager(loginStatus.groupid))){
//    return F.returnMsg(401,'权限验证失败',1);
//  }
//  var fields=Env.I;
//  var tid=fields.tid;
//  var tags=fields.tags;
//  tags=JSON.parse(tags);
//  if(tags.length==0||tags.length>3){
//    return F.returnMsg(400, '必须有一个标签且最多只能三个标签', 3);
//  }
//
//  var isTagValid=yield F.isTagValid(tags);
//  if(isTagValid.flag==false){
//    return F.returnMsg(400, isTagValid.msg, 3);
//  }
//  //先执行删除、更新标签使用次数
//  var affRow=yield mysql.query('delete from mh_thread_tags where tid=?',[tid]);
//  if(affRow.affectedRows>0){
//    var tagsData=yield mysql.queryOne('select GROUP_CONCAT(tagsid) as tags from mh_thread_tags where tid=?',[tid]);
//    if(tagsData&&tagsData['tags']){
//      var tagArray=tagsData['tags'].split(',');
//      for(var i in tagArray){
//        mysql.query('update mh_tags set tagcount=tagcount-1 where tagid=?',[tagArray[i]]);
//      }
//    }
//  }
//  // 记录标签
//  for(var i in tags){
//    var tagData=tags[i];
//    var tagsType=tagData.tagsType;
//    var tagsid=tagData.tagsid;
//    var tagstitle=tagData.tagstitle;
//    var x=tagData.x;
//    var y=tagData.y;
//    switch(tagsType){
//      case 1:
//        break;
//      case 2:
//        break;
//      case 3:
//        break;
//      case 4:
//        break;
//    }
//    mysql.query('INSERT INTO mh_thread_tags(tid,tagsid,tagstype,tagstitle,x,y) VALUES(?,?,?,?,?,?)', [tid,tagsid,tagsType,tagstitle,x,y]);
//    if(tagsType==1){
//      mysql.query('UPDATE mh_tags SET tagcount=tagcount+1 WHERE tagid=?', [tagsid]);//更新标签热度
//    }
//  }
//  return F.returnMsg(200, '成功', 3);
  return F.returnMsg(400, '此api已被整合到api10', 3);
};

/**
 @todo API12 某日网站数据
 */
exports.siteInfo = function*(Env) {
  var loginStatus = yield F.isLogin(Env);
  manLog(loginStatus, 12, '某日网站数据', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var fields = Env.I;
  var sDate = fields.sDate;
  var eDate = fields.eDate;
  if (sDate != undefined && eDate != undefined) {
    var startDate = parseInt(new Date(sDate + ' 0:0:0 CST+800').getTime() / 1000);
    var endDate = parseInt(new Date(eDate + ' 0:0:0 CST+800').getTime() / 1000) + 86400;
  } else {
    var startDate = parseInt(new Date(new Date().format('yyyy-MM-dd') + ' 0:0:0 CST+800').getTime() / 1000);
    var endDate = parseInt(new Date(new Date().format('yyyy-MM-dd') + ' 0:0:0 CST+800').getTime() / 1000) + 86400;
  }
  var loginCount = 0;
  var regCount = 0;
  var threadCount = 0;
  var postCount = 0;
  var shareCount = 0;
  var siteinfo = yield F.redisCo.hmget('siteinfo:' + startDate + '_' + endDate, ['loginCount', 'regCount', 'threadCount', 'postCount', 'shareCount']);
  if (siteinfo[0] == null) {//要查询数据不在缓存中
    var loginInfo = yield mysql.queryOne('SELECT COUNT(temp.uid) loginCount FROM(SELECT uid FROM mh_login_log WHERE timeline BETWEEN ? AND ? GROUP BY uid) temp', [startDate, endDate]);
    loginCount = loginInfo['loginCount'];

    var regInfo = yield mysql.queryOne('SELECT COUNT(uid) regCount FROM mh_user WHERE regtime BETWEEN ? AND ?', [startDate, endDate]);
    regCount = regInfo['regCount'];

    var threadInfo = yield mysql.queryOne('SELECT COUNT(tid) threadCount FROM mh_thread WHERE timeline BETWEEN ? AND ?', [startDate, endDate]);
    threadCount = threadInfo['threadCount'];

    var postInfo = yield mysql.queryOne('SELECT COUNT(pid) postCount FROM mh_post WHERE timeline BETWEEN ? AND ? AND pid NOT IN(SELECT pid FROM mh_thread WHERE timeline BETWEEN ? AND ?)', [startDate, endDate, startDate, endDate]);
    postCount = postInfo['postCount'];

    var shareInfo = yield mysql.queryOne('SELECT COUNT(shareid) shareCount FROM mh_share_log WHERE timeline BETWEEN ? AND ?', [startDate, endDate]);
    shareCount = shareInfo['shareCount'];

    F.redisClient.hmset('siteinfo:' + startDate + '_' + endDate, 'loginCount', loginCount, 'regCount', regCount, 'threadCount', threadCount, 'postCount', postCount, 'shareCount', shareCount);
    F.redisClient.expire('siteinfo:' + startDate + '_' + endDate, C.session.site_ttl);
  } else {
    loginCount = siteinfo[0];
    regCount = siteinfo[1];
    threadCount = siteinfo[2];
    postCount = siteinfo[3];
    shareCount = siteinfo[4];
  }

  var returnData = {
    'loginCount': loginCount,
    'regCount': regCount,
    'threadCount': threadCount,
    'postCount': postCount,
    'shareCount': shareCount
  };
  return F.returnMsg(200, '成功', 3, returnData);
};

/**
 @todo API13 提交升级信息
 */
exports.appUpdate = function*(Env) {
  var loginStatus = yield F.isLogin(Env);
  manLog(loginStatus, 13, '提交升级信息', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var fields = Env.I;
  var type = fields.type == undefined ? 0 : parseInt(fields.type);
  var version = fields.version;
  var code = parseInt(fields.code);
  var url = fields.url;
  var note = fields.note;
  if (!(_.v.isIn(type, [1, 2]))) {
    return F.returnMsg(400, '传递的参数错误', 1);
  }
  var isSuccess = yield mysql.query('INSERT INTO mh_app_update(os_type,version,code,url,note) VALUES(?,?,?,?,?)', [type, version, code, url, note]);
  if (isSuccess.affectedRows > 0) {
    var returnData = {
      Android: {
        version: version,
        code: code,
        url: url,
        note: note
      }
    };
    if (type == 2) {
      var returnData = {
        IOS: {
          version: version,
          code: code,
          url: url,
          note: note
        }
      };
    }
    return F.returnMsg(200, '成功', 3, returnData);
  }
};

/**
 * @todo API14 编辑标签
 * @param Env
 */
exports.editTag = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 14, '编辑标签', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var tagId = fields.tagid ? parseInt(fields.tagid) : 0;
  var tagData = yield mysql.query('SELECT * FROM mh_tags WHERE tagid=?', [tagId]);
  if (tagData.length == 0) {
    return F.returnMsg(400, '当前标签不存在' + tagId, 1);
  }
  var tagType = fields.tagtype ? parseInt(fields.tagtype) : 0;//1 系统 2自定义 3水印 4 美容标签
  var tagTitle = fields.tagtitle;//标题
  var fix = fields.fix ? parseInt(fields.fix) : 0;//1 系统 2自定义 3水印
  var tagimg = fields.imgback ? parseInt(fields.imgback) : 0;//1代表有图 0代表无图

  if (!(_.v.isIn(tagType, [1, 2, 3, 4])) || !(_.v.isIn(tagimg, [-1, 0, 1])) || !(_.v.isIn(fix, [0, 1]))) {
    return F.returnMsg(400, '传递的参数错误', 1);
  }
  if (tagTitle == '' || tagTitle == undefined) {
    return F.returnMsg(400, '标签不能为空', 1);
  }
  tagimg = tagimg == 0 ? 1 : (tagimg == 1 ? 0 : tagData[0]['tagimg']);
  if (fields.tagdesc == undefined) {
    return F.returnMsg(400, '必须传入标签描述', 1);
  }
  var fid = fields.fid || 0;//父标签id
  if (fid == tagId) {
    return F.returnMsg(400, '父标签不能是自己', 1);
  }
  if (fid != 0) {
    tagData = yield mysql.query('SELECT * FROM mh_tags WHERE tagid=?', [fid]);
    if (tagData.length == 0) {
      return F.returnMsg(400, '你选择的父标签不存在', 1);
    }
  }
  var tagDesc = fields.tagdesc;
  mysql.query('UPDATE mh_tags SET tagtype=?,tagtitle=?,tagimg=?,tagdesc=?,fid=?,fix=? WHERE tagid=?', [tagType, tagTitle, tagimg, tagDesc, fid, fix, tagId]);
  var returnData = {};
  if (tagimg == 1 || tagimg == -1) {
    var tagSignData = {};
  } else {
    // 又拍云参数

    var tagSignData = yield F.getUpyunSign({
      type: 3,
      tagId: tagId,
      imgBack: tagimg
    });

  }
  //获取水印图片签名开始
  var tagMarkSignData = {};
  if (fields.tagmark && fields.tagmark == 1) {
    tagMarkSignData = yield F.getUpyunSign({
      type: 5,
      tagId: tagId
    });
  }
  //获取水印图片签名开始

  //获取标签通栏图片签名开始
  var tagBannerSignData = {};
  if (fields.tagbanner && fields.tagbanner == 1) {
    tagBannerSignData = yield F.getUpyunSign({
      type: 6,
      tagId: tagId
    });
  }
  //获取标签通栏图片签名开始

  //删除轮播开始
  var key = C.redisPre.slider_list;
  key = _.str.sprintf(key, parseInt(tagType));
  F.redisClient.DEL(key);
  //删除轮播结束

  //更新标签信息开始
  var updateData = {};
  updateData.tagtype = tagType;
  updateData.tagtitle = tagTitle;
  updateData.tagimg = tagimg;
  updateData.tagdesc = tagDesc;
  updateData.fix = fix;
  yield F.updateTagCache(parseInt(tagId), updateData);
  //更新标签信息结束
  returnData.tagId = tagId;
  if (!_.isEmpty(tagSignData)) {
    returnData.tagSign = tagSignData;
  }
  if (!_.isEmpty(tagMarkSignData)) {
    returnData.tagMarkSign = tagMarkSignData;
  }
  if (!_.isEmpty(tagBannerSignData)) {
    returnData.tagBannerSign = tagBannerSignData;
  }
  return F.returnMsg(200, '成功', 3, returnData);
};

/**
 * @todo API15 轮播写入
 * @param Env
 */
exports.postSlider = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 15, '轮播写入', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var type = fields.type;//类型：1 标签 2 用户 3 帖子 4 lbs 5 url 6 水印标签 7 H5 8帖子列表 9百科详情 10百科帖子列表 11发日记帖
  var id = fields.id || 0;//对应的标签、用户、帖子、lbs id
  var beginTime = fields.begintime;
  var endTime = fields.endtime;
  var sstype = fields.sstype;//分类 1发现页轮播 2 首页菜单 3 水印 4 通知 5 发现页标签管理 6 置顶帖 7新发现轮播图 8发现页-圈子 9发现页-频道 10发现页-树洞 11发现页-美食
  var typeid = F.getSliderInfo(sstype).typeid;//轮播分类
  var targetUrl = fields.targeturl || '';
  var title = fields.title || '';
  var cmdStr = fields.cmdStr || '';
  var status = 0;
  if (type == 5 || type == 8) {
    id = 0;
  } else if (type != 5) {
    targetUrl = '';
  }
  if (typeid != 6 && typeid != 5) {//等于六时为置顶帖（置顶帖没有开始时间，结束时间，置顶帖默认即为有效）
    if (!(beginTime != undefined && endTime != undefined && sstype != undefined && _.v.isIn(type, [1, 2, 3, 4, 5, 6, 7, 8,9,10,11]) && _.v.isIn(sstype, C.stid_arr))) {
      return F.returnMsg(400, '传递的参数错误或必填项未填', 1);
    }
    beginTime = parseInt(new Date(beginTime + ' 0:0:0 CST+800').getTime() / 1000);
    endTime = parseInt(new Date(endTime + ' 0:0:0 CST+800').getTime() / 1000);
    if (typeid == 7 && type == 8) {//专题-帖子列表
      var cmdStrFlag = F.isJson(cmdStr);
      if (!cmdStrFlag) {
        return F.returnMsg(400, '传递的参数错误或必填项未填', 1);
      }
    }
  } else {
    if (!(_.v.isIn(type, [1, 2, 3, 4, 5, 6, 7, 8,9,10,11]) && _.v.isIn(sstype, C.stid_arr))) {
      return F.returnMsg(400, '传递的参数错误或必填项未填', 1);
    }
    status = 1;
    beginTime = 0;
    endTime = 0;
  }
  var tempData = yield mysql.query('INSERT INTO mh_slider(type,id,begintime,endtime,sstype,timeline,targeturl,title,status,cmdStr) VALUES(?,?,?,?,?,UNIX_TIMESTAMP(),?,?,?,?)', [type, id, beginTime, endTime, parseInt(sstype), targetUrl, title, status, cmdStr]);
  var aid = tempData.insertId;
  var upyun = {
    type: 4,
    aid: aid
  };

  // 如果是板块标签，则删除板块标签缓存
  if (_.v.isIn(sstype, C.slider_faxian_tags)) {
    F.redisCo.del(C.redisPre.env_brond_tagid, C.redisPre.env_tagsgroup);
  }
  //删除轮播开始
  var key = C.redisPre.slider_list;
  key = _.str.sprintf(key, parseInt(sstype));
  F.redisClient.DEL(key);
  //删除轮播结束



  var returnData = yield F.getUpyunSign(upyun);
  returnData.aid = aid;
  return F.returnMsg(200, '成功', 3, returnData);
};
/**
 * @todo API16 轮播编辑
 * @param Env
 */
exports.editSlider = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 16, '编辑轮播', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var aid = fields.aid;
  var type = fields.type;//类型：1 标签 2 用户 3 帖子 4 lbs 5 url 6 水印标签 7 H5 8帖子列表 9百科详情 10百科帖子列表 11发日记帖
  var id = fields.id || 0;//对应的标签、用户、帖子、lbs id
  var beginTime = fields.begintime;
  var endTime = fields.endtime;

  var status = fields.status;
  var targetUrl = fields.targeturl || '';
  var title = fields.title || '';
  var cmdStr = fields.cmdStr || '';
  if (type == 5 || type == 8) {
    id = 0;
  } else if (type != 5) {
    targetUrl = '';
  }
  var sliderData = yield mysql.query('SELECT aid,sstype FROM mh_slider WHERE aid=?', [aid]);
  if (sliderData.length == 0) {
    return F.returnMsg(400, '数据不存在', 1);
  }
  var typeid = F.getSliderInfo(sliderData[0].sstype).typeid;//轮播分类 1发现页轮播 2 首页菜单 3 水印 4 通知 5 发现页标签管理 6 置顶帖 7新发现轮播图 8发现页-圈子 9发现页-频道 10发现页-树洞 11发现页-美食
  if (typeid != 6 && typeid != 5) {//6为置顶帖
    if (!(beginTime != undefined && endTime != undefined && _.v.isIn(type, [1, 2, 3, 4, 5, 6, 7, 8,9,10,11]) && _.v.isIn(status, [0, 1]))) {
      return F.returnMsg(400, '传递的参数错误或必填项未填', 1);
    }
    beginTime = parseInt(new Date(beginTime + ' 0:0:0 CST+800').getTime() / 1000);
    endTime = parseInt(new Date(endTime + ' 0:0:0 CST+800').getTime() / 1000);
    if (typeid == 7 && type == 8) {//专题-帖子列表
      var cmdStrFlag = F.isJson(cmdStr);
      if (!cmdStrFlag) {
        return F.returnMsg(400, '传递的参数错误或必填项未填', 1);
      }
    }
  } else {//置顶帖
    if (typeid == 6) {
      status = 1;
    }
    if (!(_.v.isIn(type, [1, 2, 3, 4, 5, 6, 7, 8,9,10,11]) && _.v.isIn(status, [0, 1]))) {
      return F.returnMsg(400, '传递的参数错误或必填项未填', 1);
    }
    beginTime = 0;
    endTime = 0;
  }

  var tempData = yield mysql.query('UPDATE mh_slider SET type=?,id=?,begintime=?,endtime=?,`status`=?,targeturl=?,title=?,cmdStr=? WHERE aid=?', [type, id, beginTime, endTime, status, targetUrl, title, cmdStr, aid]);
  //重新设置轮播缓存开始
  var key = C.redisPre.slider_list;
  key = _.str.sprintf(key, parseInt(sliderData[0].sstype));
  var storeVal = JSON.stringify([]);
  var tmpSliderData = [];
  switch (sliderData[0].sstype) {
    case 1://发现页
    case 2://首页菜单
    case 7://新发现轮播图
      tmpSliderData = yield mysql.query("SELECT aid,type,id,begintime,endtime,targeturl,title FROM mh_slider WHERE status=1 AND sstype=? ORDER BY sort", [sliderData[0].sstype]);
      break;
    case 4://通知
      tmpSliderData = yield mysql.query("SELECT aid,type,id,begintime,endtime,timeline,targeturl,title FROM mh_slider WHERE status=1 AND sstype=? ORDER BY aid DESC ", [sliderData[0].sstype]);
      break;
    case 3://水印
      tmpSliderData = yield mysql.query("SELECT mt.tagid,mt.tagimg,mt.tagtitle,mt.fix,mt.tagdesc,ms.begintime,ms.endtime FROM mh_tags mt INNER JOIN mh_slider ms ON tagid=ms.id WHERE mt.tagtype=3 AND ms.type=1 AND ms.sstype=? AND ms.`status`=1 ORDER BY ms.sort", [sliderData[0].sstype]);
      break;
    default:
      //删除轮播开始
      F.redisClient.DEL(key);
      break;
    //删除轮播结束
  }
  if (tmpSliderData.length > 0) {
    storeVal = JSON.stringify(tmpSliderData);
    F.redisCo.SET(key, storeVal);
  }

  //重新设置轮播缓存结束
  var upyun = {
    type: 4,
    aid: aid
  };

  // 如果是板块标签，则删除板块标签缓存
  if (_.v.isIn(sliderData[0].sstype, C.slider_faxian_tags)) {
    F.redisCo.del(C.redisPre.env_brond_tagid, C.redisPre.env_tagsgroup);
  }

  var returnData = yield F.getUpyunSign(upyun);
  returnData.aid = aid;
  return F.returnMsg(200, '成功', 3, returnData);
};

/**
 * @todo API17 取轮播信息
 * @param Env
 */
exports.getSlider = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  //var fields = Env.I;
  var aid = fields.aid;
  var sliderData = yield mysql.queryOne('SELECT * FROM mh_slider WHERE aid=?', [aid]);
  if (!sliderData) {
    return F.returnMsg(300, '数据不存在', 1);
  }
  sliderData.imgUrl = F.generateSliderUrl(sliderData['aid']);
  sliderData.tagtitle = '';
  switch (sliderData.type) {
    case 1://标签
    case 6://水印标签
      var tagData = yield mysql.queryOne('SELECT tagtitle FROM mh_tags WHERE tagid=?', [sliderData.id]);
      if (tagData) {
        sliderData.tagtitle = tagData.tagtitle;
      }
      break;
    case 2://用户
      var userData = yield mysql.queryOne('SELECT nickname FROM mh_user WHERE uid=?', [sliderData.id]);
      if (userData) {
        sliderData.tagtitle = userData.nickname;
      }
      break;
    case 3://帖子
      var postData = yield  mysql.queryOne('SELECT mpc.post FROM mh_thread mt INNER JOIN mh_post_content mpc ON mt.pid=mpc.pid WHERE mt.tid=?', [sliderData.id]);
      if (postData) {
        sliderData.tagtitle = postData.post;
      }
      break;
  }
  return F.returnMsg(200, '成功', 3, sliderData);
};

/**
 * @todo API18 取轮播列表
 * @param Env
 */
exports.getSliderList = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var page = fields.page || 1;
  var pageSize = fields.pagesize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;
  var sstype = fields.sstype;
  var findVal = [];
  var findFields = [];
  findFields.push('sstype=?');
  findVal.push(sstype);
  findFields.push('1=1');
  findVal.push(beginIndex);
  findVal.push(pageSize);
  var order = 'sort';
  if (sstype == 4) {
    order = 'aid DESC';
  }
  var sliderData = yield mysql.query('SELECT * FROM mh_slider WHERE ' + findFields.join(' AND ') + ' ORDER BY ' + order + ' LIMIT ?,?', findVal);
  if (sliderData.length == 0) {
    return F.returnMsg(300, '没有数据', 1);
  }
  var slider = C.slider_type;
  for (var i in sliderData) {
    sliderData[i].tagtitle = '';
    switch (sliderData[i].type) {
      case 1://普通标签
      case 6://水印标签
        var tagData = yield mysql.queryOne('SELECT tagtitle FROM mh_tags WHERE tagid=?', [sliderData[i].id]);
        if (tagData) {
          sliderData[i].tagtitle = tagData.tagtitle;
        }
        break;
      case 2://用户
        var userData = yield mysql.queryOne('SELECT nickname FROM mh_user WHERE uid=?', [sliderData[i].id]);
        if (userData) {
          sliderData[i].tagtitle = userData.nickname;
        }
        break;
      case 3://帖子
        var postData = yield  mysql.queryOne('SELECT mpc.post FROM mh_thread mt INNER JOIN mh_post_content mpc ON mt.pid=mpc.pid WHERE mt.tid=?', [sliderData[i].id]);
        if (postData) {
          sliderData[i].tagtitle = postData.post;
        }
        break;
    }
    for (var j in slider) {
      if (slider[j]['stid'] == sliderData[i].sstype) {
        sliderData[i].typeid = slider[j].typeid;
        break;
      }
      continue;
    }
  }
  return F.returnMsg(200, '成功', 3, {pageIndex: page, items: sliderData});
};

/**
 *@todo API19 添加用户自定义标签
 * */
exports.addTag = function*(Env) {
  // 登录状态验证
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!loginStatus.status) {
    return F.returnMsg(401, '注册用户才能添加标签', 3);
  }
  var act = fields.act;
  var tagtype = 2;//默认自定义标签
  var manager = fields.manager;
  var uid = loginStatus.uid;
  if (F.isManager(loginStatus.groupid)) {
    uid = loginStatus.vestuid;
    if (manager && manager == 1) {//如果是管理员并且是后台的话可创建系统标签
      tagtype = fields.tagtype;
    }
  }
  var tagTitle = fields.tagtitle.replace(/\s+/g, ' ');
  if (tagTitle.length > 30) {
    return F.returnMsg(400, '内容超过30个字符，请修改', 1);
  }
  // 标签敏感词验证
//  if(F.isHaveSensitive(tagTitle)){
//    return F.returnMsg(400, '内容中包含有敏感词汇，请修改',1);
//  }

  // 判断标签是否存在
  var isTagExist = yield mysql.query('SELECT tagid, tagtype, tagtitle, tagcount FROM mh_tags WHERE tagtitle=?', [tagTitle]);
  if (isTagExist.length > 0) {
    return F.returnMsg(400, '该标签已经存在', 1, isTagExist);
  }
  var isSuccess = yield mysql.query('INSERT INTO mh_tags(tagtype, tagtitle, uid) values(?,?,?)', [tagtype, tagTitle, uid]);
  if (isSuccess) {
    var tags = yield mysql.query('SELECT tagid, tagtype, tagtitle, tagcount FROM mh_tags WHERE tagtitle=?', [tagTitle]);
    return F.returnMsg(200, '添加系统标签成功', 3, tags);
  } else {
    return F.returnMsg(400, '添加系统标签失败', 1);
  }
};

/**
 * @todo API20 添加版本升级信息
 * @param Env
 * @returns {*}
 */
exports.addAppUpgrate = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 20, '添加版本升级信息', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var osType = fields.ostype;
  var version = fields.version || '';
  var code = fields.code || 0;
  var url = fields.url || '';
  var note = fields.note || '';
  if (!(_.v.isIn(osType, [1, 2, 3, 4])) || !(_.v.isInt(code))) {
    return F.returnMsg(400, '传递的参数错误', 1);
  }
  var appUpdateInfo = yield mysql.query('SELECT * FROM mh_app_update WHERE code=? AND os_type=?', [code, osType]);
  if (appUpdateInfo.length > 0) {
    return F.returnMsg(400, '该版本已经存在', 1);
  }
  var insertFlag = yield mysql.query('INSERT INTO mh_app_update(os_type,version,code,url,note) VALUES(?,?,?,?,?)', [osType, version, code, url, note]);
  if (insertFlag.insertId > 0) {
    return F.returnMsg(200, '成功', 3);
  } else {
    return F.returnMsg(400, '失败', 1);
  }
};

/**
 * @todo API21 获取某个版本升级信息
 * @param Env
 * @returns {*}
 */
exports.getAppUpgrate = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 21, '获取某个版本升级信息', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var appId = fields.appid;
  var appData = yield mysql.queryOne('SELECT appid,os_type ostype,version,code,url,note,status FROM mh_app_update WHERE appid=?', [appId]);
  if (appData) {
    var splashscreenUrl = '';
    if (appData.ostype == 3 || appData.ostype == 4) {
      splashscreenUrl = F.generateSplashscreenUrl(appData.appid);
    }
    appData.splashscreenurl = splashscreenUrl;
    return F.returnMsg(200, '成功', 3, appData);
  } else {
    return F.returnMsg(300, '数据不存在', 1);
  }
};

/**
 * @todo API22 编辑版本升级信息
 * @param Env
 * @returns {*}
 */
exports.editAppUpgrate = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 22, '编辑版本升级信息', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var appId = fields.appid;
  var osType = fields.ostype;
  var version = fields.version || '';
  var code = fields.code || 0;
  var url = fields.url || '';
  var note = fields.note || '';
  var status = fields.status;
  if (!(_.v.isIn(osType, [1, 2, 3, 4])) || !(_.v.isIn(status, [0, 1])) || !(_.v.isInt(code))) {
    return F.returnMsg(400, '传递的参数错误', 1);
  }
  var appUpdateInfo = yield mysql.query('SELECT * FROM mh_app_update WHERE code=? AND os_type=? AND appid!=?', [code, osType, appId]);
  if (appUpdateInfo.length > 0) {
    return F.returnMsg(400, '该版本已经存在', 1);
  }
  var appUpdate = yield mysql.query('UPDATE mh_app_update SET os_type=?,version=?,code=?,url=?,note=?,status=? WHERE appid=?', [osType, version, code, url, note, status, appId]);
  if (appUpdate.affectedRows > 0) {
    if (osType == 3 || osType == 4) {
      var upyun = {
        type: 7,
        appId: appId
      };
      var returnData = yield F.getUpyunSign(upyun);
      returnData.appid = appId;
      return F.returnMsg(200, '成功', 3, returnData);
    } else {
      return F.returnMsg(200, '成功', 3);
    }
  } else {
    return F.returnMsg(300, '数据不存在', 1);
  }
};

/**
 * @todo API23 获取版本升级信息列表
 * @param Env
 * @returns {*}
 */
exports.getAppUpgrateList = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 23, '获取版本升级信息列表', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var page = fields.page || 1;
  var pageSize = fields.pagesize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;
  var findVal = [];
  findVal.push(beginIndex);
  findVal.push(pageSize);
  var appUpgrateData = yield mysql.query('SELECT appid,os_type ostype,version,code,url,note,status FROM mh_app_update ORDER BY appid DESC LIMIT ?,?', findVal);
  if (appUpgrateData.length == 0) {
    return F.returnMsg(300, '没有数据了', 1);
  }
  return F.returnMsg(200, '成功', 3, {pageIndex: page, items: appUpgrateData});
};

/**
 * @todo API24 取标签的关系
 * @param Env
 */
exports.getTagRelation = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 24, '取标签的关系', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var tagId = fields.tagid;
  var tagData = yield mysql.query('SELECT * FROM mh_tags WHERE tagid=?', [tagId]);
  if (tagData.length == 0) {
    return F.returnMsg(300, '当前标签不存在', 1);
  }
  var returnData = yield F.getRelation(1, tagId);
  return F.returnMsg(200, '成功', 3, returnData);
};

/**
 * @todo API25 取轮播菜单管理分类
 * @param Env
 */
exports.getSliderType = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var returnData = [];
  var sliderType = C.slider_type;
  if (sliderType) {
    returnData = sliderType;
  }
  return F.returnMsg(200, '成功', 3, returnData);
};

/**
 * @todo API26 轮播排序
 * @param Env
 */
exports.sortSlider = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 26, '轮播排序', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var sstype = parseInt(fields.sstype);
  var sliderStr = fields.sliderstr;
  if (!_.v.isIn(sstype, C.stid_arr)) {
    return F.returnMsg(400, '传递的参数错误', 1);
  }
  if (sliderStr == '') {
    return F.returnMsg(400, '没有排序的项', 1);
  }
  var sliderIdArr = sliderStr.split(',');
  var tempSliderIdArr = [];
  for (var i in sliderIdArr) {
    var sliderData = yield mysql.query('SELECT aid FROM mh_slider WHERE aid=?', [parseInt(sliderIdArr[i])]);
    if (sliderData.length != 0) {
      tempSliderIdArr.push(parseInt(sliderData[0].aid));
    }
  }
  if (tempSliderIdArr.length == 0) {
    return F.returnMsg(400, '没有排序的项', 1);
  }
  mysql.query('UPDATE mh_slider ms set ms.sort = (FIELD(aid, ' + tempSliderIdArr.join(',') + ')),ms.`status`=(IF(FIELD(aid, ' + tempSliderIdArr.join(',') + ')=0,0,1)) WHERE ms.sstype = ?', [sstype]);
  var key = C.redisPre.slider_list;
  key = _.str.sprintf(key, sstype);
  var storeVal = JSON.stringify([]);
  var tmpSliderData = [];
  switch (sstype) {
    case 1://发现页
    case 2://首页标签
    case 4://通知
    case 7://新发现轮播图
      tmpSliderData = yield mysql.query("SELECT aid,type,id,begintime,endtime,targeturl,title FROM mh_slider WHERE status=1 AND UNIX_TIMESTAMP() BETWEEN begintime AND endtime AND sstype=? ORDER BY sort", [sstype]);
      break;
    case 3://水印
      tmpSliderData = yield mysql.query("SELECT mt.tagid,mt.tagimg,mt.tagtitle,mt.fix,mt.tagdesc,ms.begintime,ms.endtime FROM mh_tags mt INNER JOIN mh_slider ms ON tagid=ms.id WHERE mt.tagtype=3 AND ms.type=1 AND ms.sstype=? AND ms.`status`=1 AND UNIX_TIMESTAMP() BETWEEN ms.begintime AND ms.endtime ORDER BY ms.sort", [sstype]);
      break;
    case 5://发现页标签
      tmpSliderData = yield mysql.query("SELECT mt.tagid,mt.tagimg,mt.tagtitle,mt.fix,mt.tagdesc,ms.begintime,ms.endtime FROM mh_tags mt INNER JOIN mh_slider ms ON tagid=ms.id WHERE (ms.type=1 or ms.type=6 ) AND ms.sstype=? AND ms.`status`=1 AND UNIX_TIMESTAMP() BETWEEN ms.begintime AND ms.endtime ORDER BY ms.sort", [sstype]);
      break;
  }
  if (tmpSliderData.length > 0) {
    storeVal = JSON.stringify(tmpSliderData);
  }
  F.redisCo.SET(key, storeVal);
  // 如果是板块标签，则删除板块标签缓存
  if (_.v.isIn(sstype, C.slider_faxian_tags)) {
    F.redisCo.del(C.redisPre.env_brond_tagid, C.redisPre.env_tagsgroup);
  }

  return F.returnMsg(200, '成功', 3);
};

/**
 * @todo API27 处理投诉
 * @param Env
 */
exports.solveComplain = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 27, '处理投诉', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var pid = fields.pid;
  if (!_.v.isInt(pid)) {
    return F.returnMsg(400, '传递的参数错误', 1);
  }
  mysql.query('UPDATE mh_post_complain SET `status`=1 WHERE pid=?', [pid]);
  return F.returnMsg(200, '处理成功', 1);
};

/**
 * @todo API28 新增模板
 * @param Env
 */
exports.addHtml = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 28, '新增模板', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var type = fields.type;//类型：1 通知
  var title = fields.title || '';
  var content = fields.content || '';
  if (title == '' || content == '' || !_.v.isIn(type, [1])) {
    return F.returnMsg(400, '传递的参数错误或必填项未填', 1);
  }
  var tempData = yield mysql.query('INSERT INTO mh_html(title,content,type,timeline) VALUES(?,?,?,UNIX_TIMESTAMP())', [title, content, type]);
  var mid = tempData.insertId;
  if (mid > 0) {
    return F.returnMsg(200, '成功', 3);
  } else {
    return F.returnMsg(400, '失败', 1);
  }
};

/**
 * @todo API29 编辑模板
 * @param Env
 */
exports.editHtml = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 29, '编辑模板', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var mid = fields.mid;
  var type = fields.type;//类型：1 通知
  var status = fields.status;
  var title = fields.title || '';
  var content = fields.content || '';

  var htmlData = yield mysql.query('SELECT mid FROM mh_html WHERE mid=?', [mid]);
  if (htmlData.length == 0) {
    return F.returnMsg(400, '数据不存在', 1);
  }
  if (title == '' || content == '' || !_.v.isIn(type, [1]) || !_.v.isIn(status, [0, 1])) {
    return F.returnMsg(400, '传递的参数错误或必填项未填', 1);
  }
  var tempData = yield mysql.query('UPDATE mh_html SET title=?,content=?,type=?,`status`=? WHERE mid=?', [title, content, type, status, mid]);
  if (tempData.affectedRows > 0) {
    return F.returnMsg(200, '成功', 3);
  }
  return F.returnMsg(400, '失败', 1);
};

/**
 * @todo API30 取模板信息
 * @param Env
 */
exports.getHtml = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var mid = fields.mid;
  var htmlData = yield mysql.queryOne('SELECT * FROM mh_html WHERE mid=?', [mid]);
  if (!htmlData) {
    return F.returnMsg(300, '数据不存在', 1);
  }
  return F.returnMsg(200, '成功', 3, htmlData);
};

/**
 * @todo API31 取模板列表
 * @param Env
 */
exports.getHtmlList = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var page = fields.page || 1;
  var pageSize = fields.pagesize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;
  var findVal = [];
  var findFields = [];

  findFields.push('1=1');
  findVal.push(beginIndex);
  findVal.push(pageSize);

  var htmlData = yield mysql.query('SELECT * FROM mh_html WHERE ' + findFields.join(' AND ') + ' ORDER BY mid desc LIMIT ?,?', findVal);
  if (htmlData.length == 0) {
    return F.returnMsg(300, '没有数据', 1);
  }
  for (var i in htmlData) {
    htmlData[i].hurl = C.h5config.hurl + htmlData[i].mid + '.html';
  }
  return F.returnMsg(200, '成功', 3, {pageIndex: page, items: htmlData});
};

/**
 * @todo API32 获取又拍云签名
 * @param Env
 */
exports.getSign = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 32, '获取又拍云签名', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var fileName = F.timestamp() + F.getRandom(4).toString();
  var upyun = {
    type: 8,
    filename: fileName
  };
  var returnData = yield F.getUpyunSign(upyun);
  returnData.fileUrl = C.upyun.h5pic_url + '/' + fileName + '.jpg';
  return F.returnMsg(200, '成功', 3, returnData);
};

/**
 * @todo API33 推送友盟广播
 * @param Env
 */
exports.umengBroadcast = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 33, '推送友盟广播', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var data = {
    msg: fields.msg,
    title: fields.title
  };
  var productionmode = (fields.productionmode == 1 ? 1 : 0);

  if (data.title.length > 15 || data.msg.length > 25) {
    return F.returnMsg(400, '标题最多15个字，内容最多25个字。', 1);
  }

  if (!(_.v.isIn(fields.os_type,[0,1,2]))) {
    return F.returnMsg(400, '参数os_type错误', 1);
  }

  if (!fields.id) F.returnMsg(400, '参数id错误', 1);
  data.act = fields.act;

  if (fields.act == 1 || fields.act == 2 || fields.act == 4) {
    if(!_.v.isInt(fields.id)||parseInt(fields.id)<1){
      return F.returnMsg(400, '参数id错误,必须传入正整数', 1);
    }
    data.id = fields.id;
  }

  if (fields.act == 3) {
    data.URL = C.h5config.hurl + fields.id + '.html';
  }

  if(fields.act ==4 || fields.act ==2){
    //验证id是否为美容日记
    var threadInfo = yield mysql.queryOne("select type from mh_thread where status=1 and fid =0 and tid = ?",[fields.id]);
    if(!threadInfo || _.isEmpty(threadInfo)){
      return F.returnMsg(400, '参数id错误,无效的帖子', 1);
    }
    var isPretty = parseInt(threadInfo['type'])==0 ? false:true;
    if(fields.act==4 && !isPretty){
      return F.returnMsg(400, '参数id错误,无效的美容日志帖', 1);
    }
    data.act = 2;
    data.type = isPretty?2:1;
  }

  var returnData = F.umengBroadcast(fields.os_type, data.act, data, productionmode);
  if (returnData.status) {
    var newUser = yield mysql.query(
      "insert into mh_broadcast_log(" +
      "timeline,os_type,title,msg,id,opname,opuid,prod_mode,type" +
      ") values(UNIX_TIMESTAMP(),?,?,?,?,?,?,?,?)",
      [fields.os_type, fields.title, fields.msg, fields.id, loginStatus.nickname, loginStatus.uid, productionmode, fields.act]);
  }
  return F.returnMsg(200, '成功', 3, returnData);
};

/**
 * @todo API34 推送友盟广播日志
 * @param Env
 */
exports.umengBroadcastLog = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var act = fields.act;
  var page = fields.page || 1;//当前页
  var pageSize = fields.pageSize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引
  var sql = "SELECT * FROM mh_broadcast_log ORDER BY bid DESC LIMIT ?,?";
  var Data = yield mysql.query(sql, [beginIndex, parseInt(pageSize)]);
  if (Data.length > 0) {
    return F.returnMsg(200, '获取成功', 3, {item: Data});
  } else {
    return F.returnMsg(300, '获取失败', 1);
  }
};

/**
 * @todo API35 帖子列表
 * @param Env
 */
exports.threads = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 35, '帖子列表', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var act = fields.act;
  var orderBy = fields.order || 'mt.tid'; //可传递的值为tid,views,replies,userreplies,liketimes,favtimes,sharetimes
  var uid = fields.uid;
  var tid = fields.tid;
  var digest = fields.digest;
  var type = fields.type;
  var nickname = fields.nickname;
  var beginTime = fields.begintime;
  var endTime = fields.endtime;
  var page = fields.page || 1;//当前页
  var pageSize = fields.pageSize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引

  var findVal = [];
  var findFields = [];
  findFields.push('1=1');

  if (uid) {
    findFields.push('mt.uid=?');
    findVal.push(parseInt(uid));
  }

  if (tid) {
    findFields.push('mt.tid=?');
    findVal.push(parseInt(tid));
  }

  if (digest) {
    findFields.push('mt.digest=?');
    findVal.push(parseInt(digest));
  }

  if (type) {
    findFields.push('mt.type=?');
    findVal.push(parseInt(type));
  }

  if (beginTime && endTime) {
    beginTime = parseInt(new Date(beginTime + ' CST+800').getTime() / 1000);
    endTime = parseInt(new Date(endTime + ' CST+800').getTime() / 1000);
    findFields.push('mt.timeline BETWEEN ? AND ?');
    findVal.push(beginTime);
    findVal.push(endTime);
  }

  if (nickname) {
    findFields.push('mu.nickname REGEXP ?');
    findVal.push(nickname);
  }

  findVal.push(beginIndex);
  findVal.push(pageSize);

  var Data = yield mysql.query('SELECT mt.tid,mt.uid,mt.views,mt.replies,mt.userreplies,mt.uliketimes,mt.timeline,mt.closed,mt.status,mt.digest,mt.favtimes,mt.sharetimes,mt.liketimes,mt.type,mt.accesslevel,mu.nickname FROM mh_thread mt LEFT JOIN mh_user mu ON mt.uid=mu.uid WHERE ' + findFields.join(' AND ') + ' ORDER BY ' + orderBy + ' desc LIMIT ?,?', findVal);
  if (Data.length > 0) {
    return F.returnMsg(200, '获取成功', 3, {item: Data});
  } else {
    return F.returnMsg(300, '获取失败', 1);
  }
};

/**
 * @todo API36 达人申请列表
 * @param Env
 */
exports.talentApplyList = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 36, '达人申请列表', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var act = fields.act;
  var page = fields.page || 1;//当前页
  var pageSize = fields.pageSize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引

  var findVal = [];
  var findFields = [];
  findFields.push('1=1');

  findVal.push(beginIndex);
  findVal.push(pageSize);

  var data = yield mysql.query('SELECT mta.alid,mta.uid,mta.timeline,mta.talentid,mu.nickname FROM mh_talent_asklog mta LEFT JOIN mh_user mu on mu.uid=mta.uid WHERE mta.status=0 ORDER BY mta.alid DESC LIMIT ?,?', findVal);
  if (data.length > 0) {
    for (var i in data) {
      var talentInfo = F.getTalentInfo(data[i].talentid);
      data[i].talentname = talentInfo.name;
      delete data[i].talentid;
    }
    return F.returnMsg(200, '获取成功', 3, {item: data});
  } else {
    return F.returnMsg(300, '获取失败', 1);
  }
};

/**
 * @todo API37 取一条达人申请信息
 * @param Env
 */
exports.talentApplyInfo = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 37, '取一条达人申请信息', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var alid = fields.alid;
  var tempData = yield mysql.queryOne('SELECT mta.*,mu.nickname FROM mh_talent_asklog mta LEFT JOIN mh_user mu on mu.uid=mta.uid WHERE mta.alid=?', [alid]);
  if (!tempData) {
    return F.returnMsg(300, '数据不存在', 1);
  }
  var talentInfo = F.getTalentInfo(tempData.talentid);
  delete tempData.status;
  delete tempData.talentid;
  tempData.talentname = talentInfo.name;
  return F.returnMsg(200, '成功', 3, tempData);
};

/**
 * @todo API38 审批达人申请
 * @param Env
 */
exports.answerTalentApply = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 38, '审批达人申请', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var alid = fields.alid;
  var status = fields.status;
  var tempData = yield mysql.queryOne('SELECT * FROM mh_talent_asklog WHERE alid=?', [alid]);
  if (!tempData) {
    return F.returnMsg(300, '数据不存在', 1);
  }
  if (!(_.v.isIn(status, [1, 2]))) {
    return F.returnMsg(400, '传递的参数错误。', 1);
  }
  mysql.query('UPDATE mh_talent_asklog set `status`=?,apptime=UNIX_TIMESTAMP() WHERE alid=?', [status, alid]);
  if (status == 1) {
    var userInfo = yield F.returnUserInfo(tempData.uid);
    userInfo = userInfo[0];
    var updateUserCache = {};
    updateUserCache.talentid = tempData.talentid;
    var level = F.getLevelfromIntegral(userInfo.integral);
    var talent = F.getTalentInfo(tempData.talentid).name;
    var talent_level = level.talent_level; //  this.getTalentInfo(threads[i].talentid).talent_level;
    updateUserCache.talent_level = talent_level;
    updateUserCache.talent = talent;
    yield F.updateUserCache(parseInt(tempData.uid), updateUserCache);//更新用户缓存
    mysql.query('UPDATE mh_user_info set `talentid`=? WHERE uid=?', [tempData.talentid, tempData.uid]);

  }
  return F.returnMsg(200, '成功', 3);
};

/**
 * @todo API39 登录日志
 * @param Env
 */
exports.getLoginLog = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 39, '登录日志', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2, 3]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var uid = fields.uid || loginStatus.uid;
  var page = fields.page || 1;//当前页
  var pageSize = fields.pageSize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引

  var tempData = yield mysql.query('SELECT os_type,ip,channelid,appver,timeline FROM mh_user_log WHERE uid=? ORDER BY logid DESC LIMIT ?,?', [uid, beginIndex, pageSize]);
  if (tempData.length == 0) {
    return F.returnMsg(300, '数据不存在', 1);
  }
  return F.returnMsg(200, '成功', 3, tempData);
};

/**
 * @todo API40 获取登录用户地理位置信息
 * @param Env
 */
exports.getUsersGeo = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 40, '获取登录用户地理位置信息', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var timeRange = fields.timerange || 2;
  timeRange = parseInt(timeRange);
  var endTime = F.timestamp();//结束时间
  var beginTime = endTime - timeRange * 60 * 60;

  var tempData = yield mysql.query('SELECT geoLat,geoLng FROM (SELECT * FROM mh_user_geo_log WHERE timeline BETWEEN ? AND ? ORDER BY timeline DESC LIMIT 10000)  tmpdb GROUP BY  uid ORDER BY timeline DESC', [beginTime, endTime]);
  if (tempData.length == 0) {
    return F.returnMsg(300, '数据不存在', 1);
  }
  return F.returnMsg(200, '成功', 3, tempData);
};

/**
 * @todo API41 统计报表
 * @param Env
 */
exports.siteReport = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 41, '统计报表', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var tempData = [];
  var act = fields.act;

  var page = fields.page || 1;//当前页
  var pageSize = fields.pageSize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引

  var sDate = fields.sDate;
  var eDate = fields.eDate;
  if (sDate != undefined && eDate != undefined) {
    var startDate = parseInt(new Date(sDate + ' 0:0:0 CST+800').getTime() / 1000);
    var endDate = parseInt(new Date(eDate + ' 0:0:0 CST+800').getTime() / 1000) + 86400;
  } else {
    var startDate = parseInt(new Date(new Date().format('yyyy-MM-dd') + ' 0:0:0 CST+800').getTime() / 1000);
    var endDate = parseInt(new Date(new Date().format('yyyy-MM-dd') + ' 0:0:0 CST+800').getTime() / 1000) + 86400;
  }

  sDate = new Date(startDate * 1000).format('yyyy-MM-dd');
  eDate = new Date(endDate * 1000).format('yyyy-MM-dd');


  // act==1 取菜单
  if (act == 1) {
    return F.returnMsg(200, '成功', 3, {
      title: '统计报表',
      menu: [
        {'title': '登录人数统计', 'cmd': '{"act":2}'},
        {'title': '注册人数统计', 'cmd': '{"act":3}'},
        {'title': '下载列表', 'cmd': '{"act":4}'}

      ]
    });

    // 登录统计表
  } else if (act == 2) {
    if (page == 1) {
      tempData = yield mysql.query('SELECT DATE_FORMAT(DATE(FROM_UNIXTIME(mll.timeline)),\'%Y-%m-%d\') as 日期, count(DISTINCT mll.uid) as 人数 FROM mh_login_log mll LEFT JOIN mh_user mu ON mu.uid = mll.uid WHERE mll.timeline>=? AND mll.timeline<? AND DATE(FROM_UNIXTIME(mu.regtime)) <> DATE(FROM_UNIXTIME(mll.timeline)) GROUP BY DATE(FROM_UNIXTIME(mll.timeline)) ORDER BY mll.timeline DESC', [startDate, endDate]);
    }
    // 注册统计表
  } else if (act == 3) {
    if (page == 1) {
      tempData = yield mysql.query('SELECT DATE_FORMAT(DATE(FROM_UNIXTIME(mu.regtime)),\'%Y-%m-%d\') as 日期, COUNT(mu.uid) as 人数 FROM mh_user mu WHERE mu.regtime>=? AND mu.regtime<? GROUP BY DATE(FROM_UNIXTIME(mu.regtime)) ORDER BY mu.regtime DESC', [startDate, endDate]);
    }
  }
  else if (act == 4) {
    tempData = yield mysql.query('SELECT os_type as 设备类型,version as 版本,channel as 渠道,DATE_FORMAT(timeline,\'%Y-%m-%d\') as 下载时间' +
      ' FROM mh_app_download_log' +
        //' WHERE (channel IN(\'yueni1\',\'yueni2\',\'yueni3\',\'yueni4\'))' +
      ' WHERE (timeline >= ? and timeline <?)' +
      ' GROUP BY ip ORDER BY did DESC LIMIT ?,?', [sDate, eDate, beginIndex, pageSize]);
  }
  if (tempData.length == 0) {
    return F.returnMsg(300, '数据不存在', 3);
  }
  return F.returnMsg(200, '成功', 3, {title: '每日登录用户统计(不含新注册)', data: tempData});
};

/**
 * @todo API42 活动统计报表
 * @param Env
 */
exports.activityReport = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 42, '活动统计报表', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var tempData = [];
  var act = fields.act;

  var page = fields.page || 1;//当前页
  var pageSize = fields.pageSize || C.manager_pageSize;
  var beginIndex = (page - 1) * pageSize;//开始索引

  // act==1 取菜单
  if (act == 1) {
    return F.returnMsg(200, '成功', 3, {
      title: '活动统计报表',
      menu: [
        {'title': '领取验证码报表', 'cmd': '{"act":2}'},
        {'title': '兑换验证码报表', 'cmd': '{"act":3}'}
      ]
    });

    // 领取验证码报表
  } else if (act == 2) {
    tempData = yield mysql.query('select mu.uid as 用户编号,mu.nickname as 用户昵称,moc.mobile as 电话,moc.captcha as 验证码,DATE_FORMAT(DATE(FROM_UNIXTIME(mo.date)),\'%Y-%m-%d\') as 获取日期 from mh_order_captcha moc ' +
      ' inner join mh_order mo on moc.orderid=mo.orderid ' +
      ' inner join mh_user mu on mo.uid=mu.uid order by mo.date LIMIT ?,?', [beginIndex, pageSize]);
    // 兑换验证码报表
  } else if (act == 3) {
    tempData = yield mysql.query('select mu.uid as 用户编号,mu.nickname as 用户昵称,moc.mobile as 电话,moc.captcha as 验证码,DATE_FORMAT(DATE(FROM_UNIXTIME(mo.date)),\'%Y-%m-%d\') as 获取日期,' +
      ' DATE_FORMAT(DATE(FROM_UNIXTIME(moc.exchangetime)),\'%Y-%m-%d\') as 兑换日期,mw.wshopid as 店面id,mw.name as 店面名称, mw.shopaddress as 店面地址 from mh_order_captcha moc' +
      ' inner join mh_order mo on moc.orderid=mo.orderid' +
      ' inner join mh_user mu on mo.uid=mu.uid' +
      ' INNER JOIN mh_watsons mw on mw.wshopid=moc.shopid and moc.shopid<>\'\'' +
      ' order by moc.exchangetime LIMIT ?,?', [beginIndex, pageSize]);
  }
  if (tempData.length == 0) {
    return F.returnMsg(300, '数据不存在', 3);
  }
  return F.returnMsg(200, '成功', 3, {title: '活动统计报表)', data: tempData});
};

/**
 * @todo API43 帖子类别维护
 * @param Env
 */
exports.threadCategoryInfo = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 43, '帖子类别维护', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var tempData = [];
  var act = fields.act;
  var cid = parseInt(fields.cid) || 0;
  if (act == 2 || act == 3) {//更新跟删除的时候验证cid
    if (cid < 1) return F.returnMsg(300, 'cid 格式错误', 1);

  }
  var mCategory = require('../model/mCategory.js');
  var modelCategory = {
    cid: cid,
    name: fields.name || '',
    ctype: fields.ctype != undefined ? parseInt(fields.ctype) : -1,
    pcid: fields.pcid != undefined ? parseInt(fields.pcid) : -1,
    detail: fields.detail || '',
    status: fields.status != undefined ? parseInt(fields.status) : -1,
    categoryimg: fields.categoryimg || '',
    sort: fields.sort || 0,
    sliderstr: fields.sliderstr || '',
    latest: fields.latest != undefined ? parseInt(fields.latest) : -1,
    threadstatus:fields.threadstatus!=undefined?parseInt(fields.threadstatus):-1
  };
  var entityCategory = new mCategory.threadCategory(modelCategory);
  if (act == 1 || act == 2) {//保存帖子类别
    let ret = yield entityCategory.save();
    return F.returnMsg(200, ret.msg, 3);
  } else if (act == 3) {//删除帖子类别
    let ret = yield entityCategory.delete();
    return F.returnMsg(200, ret.msg, 3);
  } else if (act == 4) {//查询帖子类别
    //entityCategory.status=fields.status || 1;
    let ret = yield entityCategory.query();
    if (!(ret.data && ret.data.length > 0)) {
      return F.returnMsg(300, '数据不存在', 3);
    }
    return F.returnMsg(200, '获取成功.', 3, ret.data);
  } else if (act == 5) {//自增帖子类别
    let ret = yield entityCategory.increaseSort();
    return F.returnMsg(200, ret.msg, 3);
  }
};

/**
 * @todo API44  修改帖时,帖子图片上传成功后的Callback
 * @param Env
 */
exports.postEditImgCallback = function*(Env) {
  //验证登陆
  //let loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!loginStatus.status) return F.returnMsg(400, '必须登录', 3);


  //必须有tid
  if (!fields.tid) return F.returnMsg(400, '必须有tid', 3);
  //fields.imgStrArr = '[{"index":0,"imgStr":"P-25695-370128.jpg"},{"index":1,"imgStr":"P-25695-370128.jpg"}]';

  //转换imgStrArr
  let imgStrArr = [];
  try {
    imgStrArr = JSON.parse(fields.imgStrArr);
  } catch (err) {
    return F.returnMsg(200, 'imgStrArr有错', 3, err);
  }

  //查询tid对应的图片
  let retPostImgArr = yield mysql.query('select imagestring from mh_thread where tid=?', [fields.tid]);
  //替代之前的图片
  let retArr = retPostImgArr[0].imagestring.split(',');
  for (let i in retArr) {
    for (let one of imgStrArr) {
      if (one.index == i) {
        retArr[i] = one.imgStr;
      }
    }
  }
  let newImgStr = retArr.toString();
  //修改图片
  let ret = yield mysql.query('UPDATE mh_thread SET imagestring=? WHERE tid=?', [newImgStr, fields.tid]);//修改数据库中的图
  return F.returnMsg(200, 'ok', 3);
};



/**
 * @todo API45  帖子类别修改
 * @param Env
 */
exports.threadCategory = function*(Env){
  let fields = Env.I;
  let act = parseInt(fields.act);
  let loginStatus = fields.loginStatus;
  manLog(loginStatus, 45, '帖子类别修改', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }

  if(typeof fields.tid=='undefined' || parseInt(fields.tid)<=0){
    return F.returnMsg(400, '操作的主题帖不存在', 1);
  }
  let tid = parseInt(fields.tid);
  //判断帖子是否存在
  let threadInfo =yield mysql.query("select tid,cid,uid from mh_thread where tid=? ",[tid]);
  if(threadInfo.length==0){
    return F.returnMsg(400, '操作的主题帖不存在', 1);
  }
  let oldcid =parseInt(threadInfo[0]['cid']);
  if(act==1){
    //验证cid,tid类型,cid=0成立
    if(typeof fields.cid=='undefined' || parseInt(fields.cid)<0){
      return F.returnMsg(400, '请选择一个正确分类', 1);
    }
    let cid = parseInt(fields.cid);
    //更新新数据信息，分类id有改动才执行
    if(cid!=oldcid){
      //判断cid是否合法
      let cateData = yield  mysql.query("SELECT cid,threadstatus,name,pcid,status FROM `mh_thread_category` WHERE cid=? AND pcid>0 AND status=1",[cid]);
      if(cateData.length==0){
        return F.returnMsg(400, '该分类已设为无效，请先有效该类别', 1);
      }
      let name =cateData[0]['name'];
      //更新thread表分类
      let res =yield mysql.query("UPDATE `mh_thread` SET cid=?,ctype=1 WHERE tid =? ",[cid,tid]);
      if(res.affectedRows==0){
        return F.returnMsg(400, '修改分类操作失败', 1);
      }

      //通知中勤那边修改
      var json = {
        uid: loginStatus.uid,
        tid: tid,
        action: 'edit',
        cid: cid,
        ctype:1
      };
      logstash.article(json);


      //更新catergory分类表,主贴表中的cid有部分为9999
      if(oldcid != parseInt(C.threadlist.defaultThreadCategory)){
        let oldcate = yield  mysql.query("SELECT cid,threads FROM `mh_thread_category`  WHERE cid =? ",[oldcid]);
        if(oldcate[0]['threads']>0){
          yield mysql.query("UPDATE `mh_thread_category` SET threads = threads-1 WHERE cid =? ",[oldcid]);
        }
      }
      //更新更改的分类帖子数
      yield mysql.query("UPDATE `mh_thread_category` SET threads= threads+1 WHERE cid =? ",[cid]);

      //更新redis缓存，更新thread_info缓存
      var threadcache = yield F.returnThreadInfo(tid);
      if(threadcache.length>0){
        threadcache[0]['cid']= cid;
        threadcache[0]['categoryname']= name;
        threadcache[0]['ctype']= 1;
        yield F.updateThreadCache(tid, threadcache[0]);
      }
      return F.returnMsg(200, '更新分类成功！', 3, {tid: tid, cid: cid, oldcid: oldcid,name:name});
    }else{
      return F.returnMsg(200, '更新分类成功！', 3, {tid: tid, cid: cid, oldcid: oldcid});
    }
  }
  return F.returnMsg(400, '修改分类操作失败', 1);
}


/**
 * 后台获取o2o一级二级分类信息
 */
exports.geto2oCate = function*(){
  //获取o2o一级二级分类信息
  let body ={act:2,type:3,depth:3}
  let topCate = yield F.geto2oCategoryList(body,"list");
  topCate = topCate.result;

  return F.returnMsg(200,'获取o2o分类成功',1,topCate);
}


/**
 * 后台添加o2o三级标签
 * @param Env
 */
exports.addo2oTag = function*(Env){
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  //权限鉴定
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  let tagname = _.str.trim(fields.tagname);
  if(!tagname){
    return F.returnMsg(400, '标签名不存在！', 1);
  }
  let pCode = parseInt(fields.pCode);
  if(!pCode){
    return F.returnMsg(400, 'pCode参数不存在！', 1);
  }
  //获取o2o一级二级分类信息
  let body ={act:1,type:3,pCode:0}
  let topCate = yield F.geto2oCategoryList(body,"list");
  topCate = topCate.result;
  let tag= false;//console.log(topCate);
  for(let i in topCate){
    let code = topCate[i]["code"];
    let children = yield F.geto2oCategoryList({act:1,type:3,pCode:code},"list");
    topCate[i]['children']=children.result;
    //判断pCode是否存在
    for(let n in children.result){
      if(children.result[n]['code']==pCode){
        tag = true;break;
      }
    }
  }
  //验证pCode是否合法
  if(!tag){
    return F.returnMsg(400, '参数错误，pcode必须是二级！', 1);
  }
  //添加o2o第三级标签
  let rs =  yield F.geto2oCategoryList({act:1,name:tagname,type:3,pCode:pCode},"add");
  if(rs.status==200){
    return F.returnMsg(200,'添加成功',1,{name:tagname,pCode:pCode});
  }
  return F.returnMsg(400,'添加失败',1);
}


/**
 * @todo 瀑布.im
 * @param Env
 */
exports.pubuImInfo = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  manLog(loginStatus, 43, 'pubuim_test', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var msg = fields.mgs;
  var mPubuIM = require('../model/mPubuIM.js');
  var pubuIM = new mPubuIM.pubuIM({cid: cid});
  pubuIM.name = fields.name;
  if (act == 1 || act == 2) {
    let ret = yield pubuIM.send();
    return F.returnMsg(200, 'test', 3);
    //return F.returnMsg(200, ret.msg, 3);
  } else {
    let ret = yield pubuIM.send();
    return F.returnMsg(200, 'test', 3);
  }
};

exports.getWatsonsGeo = function*(Env) {
  var jsdom = require("jsdom");

  var fields = Env.I;
  let act = fields.act;
  let districtAreaName = fields.district;
  var path = require("path");
  //var jquery = path.resolve("D:/SVN_Code/API/node_modules/jquery/dist/jquery.min.js");
  var jquery = path.resolve(__dirname, '../jquery/jquery-1.11.3.min.js');
  let logNumber = 1;

  let options = {
    url: '',
    headers: {'User-Agent': 'request', 'referer': 'http://admin.yueniapp.com/user.html'},
    method: 'GET',
    timeout: 50000
  };
  if (act == 1) {//取得广州所有区
    let cityId = 4;
    options.url = 'http://www.dianping.com/search/category/' + cityId + '/50/g158';
    let home = yield request(options);
    let html = home.body;
    jsdom.env(
      html,
      [jquery],
      function (errors, window) {
        var $ = window.$;
        //var storeArr=Array.prototype.slice.apply($("#region-nav a"));
        $("#region-nav a").each(function () {
          let districtURL = $(this).attr('href');///search/category/4/50/g158r24#nav-tab|0|1
          let districtName = $(this).find('span').text();
          let sql = ' where not exists(select 1 from mh_dianping_DistrictBussiness where region_type=1 and city =\'' + cityId + '\' and district =\'' + districtName + '\')';
          mysql.query('INSERT INTO mh_dianping_DistrictBussiness(region_type,city,district,district_url) select 1,?,?,? from dual ' + sql, [cityId, districtName, districtURL]);
        });
      });
  }
  if (act == 2) {//取得所有商圈
    let cityid = 4;
    let districtArea = yield mysql.query('select city,district,district_url from mh_dianping_DistrictBussiness where region_type=1 and city=?', [cityid]);
    for (let i in districtArea) {
      let url = districtArea[i].district_url;
      options.url = 'http://www.dianping.com' + url;
      let home = yield request(options);
      let html = home.body;
      jsdom.env(
        html,
        [jquery],
        function (errors, window) {
          var $ = window.$;
          //var page2Url=$(".page a[Class='PageLink'][title='2']").attr('href');
          //var districtArr=Array.prototype.slice.apply($("#region-nav-sub a"));
          $("#region-nav-sub a").each(function () {
            let businessURL = $(this).attr('href');
            let businessName = $(this).find('span').text();
            if (businessName != '不限') {
              console.log(businessName);
              console.log(businessURL);
              // console.log(page2Url);
              console.log(districtArea[i].district);
              let sql = ' where not exists(select 1 from mh_dianping_DistrictBussiness where region_type=2 and district =\'' + districtArea[i].district + '\' and business_area =\'' + businessName + '\' and business_area_url =\'' + businessURL + '\')';
              mysql.query('INSERT INTO mh_dianping_DistrictBussiness(region_type,city,district,business_area,business_area_url) select 2,?,?,?,? from dual ' + sql, [cityid, districtArea[i].district, businessName, businessURL]);
            }
          });
        });
    }
  }
  else if (act == 3) {
    let cityid = 4;
    //let districtAreaName='荔湾区';
    let districtArea = yield mysql.query('select business_area_url from mh_dianping_DistrictBussiness where region_type=2 and city=? and district=? order by sort desc', [cityid, districtAreaName]);
    console.log(districtArea.length);
    for (let i in districtArea) {
      let businessURL = districtArea[i].business_area_url;
      businessURL = businessURL.split('#')[0];
      for (let j = 1; j <= 50; j++) {
        options.url = 'http://www.dianping.com' + businessURL + 'p' + j;
        if (j > 1) {
          options.url = options.url + '?aid=b3ff919c132da0ad633d23ca9720a99bcd0ff7304a4e292bf5b46dd9979baffbd674b18e6d50a91f78536a6c9c44e07df79255ec2f0668e05f4276f2ced8f6f1&tc=2';
        }
        try {
          var home = yield request(options);
          var html = home.body || '';
          if (html == '' || html.indexOf('没有找到相应的商户') > -1) {
            break;
          } else if (html.indexOf('您使用的IP访问网站过于频繁') > -1) {
            console.log('request failure.');
          }
          console.log('request time:' + logNumber);
          logNumber++;
        }
        catch (e) {
          console.log(e);
          break;
        }
        jsdom.env(
          html,
          [jquery],
          function (errors, window) {
            var $ = window.$;
            //var storeArr=Array.prototype.slice.apply($("#shop-all-list li .pic a"));
            $("#shop-all-list li .pic a").each(function () {
              if (errors) {
                console.log(errors.msg)
              }
              let shopid = $(this).attr('href');
              let imgurl = $(this).find('img').attr('data-src');
              let sql = ' where not exists(select 1 from mh_dianPingStore where shopid =\'' + shopid + '\')';
              mysql.query('INSERT INTO mh_dianPingStore(shopid,photoSrc) select ?,? from dual ' + sql, [shopid, imgurl]);
            });
          });
      }
    }
  } else if (act == 4) {
    let shopidArr = yield mysql.query('select shopid from mh_dianPingStore where hasInsert=0 or length(name)=0');
    for (let i in shopidArr) {
      options.url = "http://www.dianping.com" + shopidArr[i].shopid;
      console.log(options.url);
      try {
        let home = yield request(options);
        var html = home.body;
        if (html.indexOf('您使用的IP访问网站过于频繁') > -1) {
          console.log('request failure.');
        }
        console.log('request time:' + logNumber);
        logNumber++;
      }
      catch (e) {
        console.log(e);
        break;
      }
      // var fs = require("fs");
      // fs.writeFile('shop.html',html);
      jsdom.env(
        html,
        [jquery],
        function (errors, window) {
          var $ = window.$;
          let store = {};
          store.shopName = $("h1").text().replace($("h1 a").text(), '').trim();
          console.log('name: ' + store.shopName);
          store.address = _.str.join($("span[itemprop='locality region']").text(), $("span[itemprop='street-address']").text()).trim();
          console.log('address: ' + store.address);
          let telArr = Array.prototype.slice.apply($(".tel.expand-info span[itemprop='tel']"));
          let telNumberArr = [];
          for (let j in telArr) {
            telNumberArr.push($($(".tel.expand-info span[itemprop='tel']")[j]).text());
          }
          store.tel = telNumberArr.join(',');
          console.log('tel: ' + store.tel);
          store.otherInfo = $("p[class='info info-indent']").text().replace("修改", '').replace("添加", '').trim().replace(/\s+/g, ' ');
          store.otherInfo = store.otherInfo.substring(0, store.otherInfo.indexOf('网友推荐'));
          console.log('other info:' + store.otherInfo);

          let patt = /{lng:([1-9]\d*\.\d*),lat:([1-9]\d*\.\d*)}/mg;
          let arr = patt.exec(html);
          if (arr && arr.length > 0) {
            store.lng = arr[1]
            store.lat = arr[2];
          }
          mysql.query('update mh_dianPingStore set name=?,address=?,tel=?,lng=?,lat=?,otherInfo=?,hasInsert=? where shopid=?',
            [store.shopName, store.address, store.tel, store.lng, store.lat, store.otherInfo, 1, shopidArr[i].shopid]);
        });
    }
  } else if (act == 5) {
    //let shopLoc=yield mysql.query('select lng,lat,shopid from mh_dianPingStore where hasInsert=1 and length(lng)>0');
    let shopLoc = yield mysql.query('select lng,lat,shopid from mh_dianPingStore where length(lng)>0');
    for (let k in shopLoc) {
      options.url = 'http://restapi.amap.com/v3/geocode/regeo?location=' + shopLoc[k].lng + ',' + shopLoc[k].lat + '&key=891276fb426e6b189d23c1376f05feca&s=rsv3&radius=1000&extensions=all';
      try {
        let home = yield request(options);
        let region_json = JSON.parse(home.body).regeocode.addressComponent;
        delete region_json.neighborhood;
        delete region_json.building;
        let region = [];
        let busiArea = region_json.businessAreas[0].name;
        console.log(k);
        if (busiArea === undefined) {
          console.log('商圈：' + region_json.businessAreas[0]);
        }
        let businessRd = yield mysql.queryOne('select region_id from mh_business_region where parent_id=? and region_name=?', [region_json.adcode, region_json.businessAreas[0].name]);
        region.push(
          {name: region_json.province, level: 1, pCode: 0, code: region_json.adcode.substring(0, 2) + '0000'},
          {
            name: region_json.city,
            level: 2,
            pCode: region_json.adcode.substring(0, 2) + '0000',
            code: region_json.adcode.substring(0, 4) + '00'
          },
          {
            name: region_json.district,
            level: 3,
            pCode: region_json.adcode.substring(0, 4) + '00',
            code: region_json.adcode
          }
        );
        if (businessRd) {
          region.push({
            name: region_json.businessAreas[0].name,
            level: 4,
            pCode: region_json.adcode,
            code: businessRd['region_id']
          });
        }
        region.push({name: region_json.township, level: 4, pCode: region_json.adcode, code: '000'});
        yield mysql.query('UPDATE mh_dianPingStore set regions=?,otherInfo1=?,hasInsert=? where shopid=?', [JSON.stringify(region), JSON.stringify(region_json), 2, shopLoc[k].shopid]);
      } catch (e) {
        console.log(e.msg)
      }
    }
  }
};

exports.jsdomfu = function* (url, jquery) {
  var jsdom = require("jsdom");
  let options = {
    url: url,
    headers: {'User-Agent': 'request', 'referer': 'http://admin.yueniapp.com/user.html'},
    method: 'GET',
    timeout: 5000
  };
  var result;
  var home = yield request(options);
  var html = home.body;
  let ret = yield jsdom.env(html, [jquery], function (errors, window) {
    result = window;
  });
  return result;
};

exports.testFun = function*() {
  //let b =  $(this).attr('href');
  //console.log(imgRule.str2imgURI('S-1234567-654321.jpg'));
  //console.log(imgRule.id2imgStr('S', 1234567, 'jpg'));
  let retData = {};
  retData.id2imgStr = imgRule.id2imgStr('w', 1234567, 'jpg', 'abc');
  retData.str2imgURI = imgRule.str2imgURI(retData.id2imgStr);
  //retData.str2imgURI = imgRule.str2imgURI('W-1234567-654321.jpg');
  let proc = retData.str2imgURI[0];
  //proc.crop =
  retData.sign = yield F.getUpyunSignB(proc);
  return F.returnMsg(200, 'ok', 3, retData);
  /*
   var jsdom = require("jsdom");

   var homeURL = 'http://www.dianping.com/search/category/4/50/g158';
   let options = {
   url: homeURL,
   headers: {'User-Agent': 'request'},
   method: 'GET',
   timeout: 5000
   };
   var path = require ("path");
   var jquery = path.resolve("D:/SVN_Code/API/node_modules/jquery/dist/jquery.min.js");
   let home = yield request(options);
   var html=home.body;
   var storeIdArr=[];
   var storeArr=[];

   for(let j in storeIdArr){
   //http://www.dianping.com/
   options.url=_.str.join("http://www.dianping.com/",storeIdArr[j]);
   home=yield request(options);
   html=home.body;

   jsdom.env(
   html,
   [jquery],
   function (errors, window) {
   var $ = window.$;
   let store={};
   store.shopName=$("h1").text().replace($("h1 a").text(),'');
   console.log('name: '+store.shopName);
   store.address=_.str.join($("span[itemprop='locality region']").text(),$("span[itemprop='street-address']").text());
   console.log('address: '+store.address);
   store.tel=$("span[itemprop='tel']").text();
   console.log('tel: '+store.tel);
   store.otherInfo=$("p[class='info info-indent']").text().replace("修改",'');
   console.log('other info:'+store.otherInfo);
   });
   }*/
};
exports.getWatsonsGeoBusinessArea = function*(Env) {
  var options = {
    headers: {'User-Agent': 'request', 'referer': 'http://admin.yueniapp.com/user.html'},
    method: 'GET',
    timeout: 5000
  };
  var provinceList = ['北京市', '天津市', '河北省', '山西省', '内蒙古自治区', '辽宁省', '吉林省', '黑龙江省', '上海市', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', '湖北省', '湖南省', '广东省', '广西壮族自治区', '海南省', '重庆市', '四川省', '贵州省', '云南省', '西藏自治区', '陕西省', '甘肃省', '青海省', '宁夏回族自治区', '新疆维吾尔自治区', '台灣', '香港特别行政区', '澳门特别行政区'];

  for (let i in provinceList) {
    options.url = 'http://restapi.amap.com/v3/config/district?subdistrict=3&extensions=all&level=province&key=891276fb426e6b189d23c1376f05feca&s=rsv3&output=json&keywords='
      + encodeURI(provinceList[i]);
    let home = yield request(options);
    // console.log(home.body);
    let provinceDistinct = JSON.parse(home.body);
    if (provinceDistinct.count == 0) {
      continue;
    }
    let regionCode = provinceDistinct.districts[0].adcode;
    let regionName = provinceDistinct.districts[0].name;
    let cityCode = provinceDistinct.districts[0].citycode;
    let region_type = 1;
    let regionLocation = provinceDistinct.districts[0].center;
    //Level1 province
    let sql = ' where not exists(select 1 from mh_business_region where region_id =\'' + regionCode + '\' and region_name=\'' + regionName + '\' and region_type=' + region_type + ')';
    console.log('省 ' + regionName + '  ' + regionCode);
    yield mysql.query('insert into mh_business_region(region_id,region_name,region_type,center_location) select ?,?,?,? from dual' + sql, [regionCode, regionName, region_type, regionLocation]);
    //level2 city
    let cityDistinct = provinceDistinct.districts[0].districts;
    let cityRegionCode = regionCode;
    for (let i in cityDistinct) {
      regionCode = cityDistinct[i].adcode;
      regionName = cityDistinct[i].name;
      regionLocation = cityDistinct[i].center;
      cityCode = cityDistinct[i].citycode;
      region_type = 2;
      let sql = ' where not exists(select 1 from mh_business_region where region_id =\'' + regionCode + '\' and region_name=\'' + regionName + '\' and parent_id=\'' + cityRegionCode + '\' and region_type=' + region_type + ')';
      console.log('市 ' + regionName + '  ' + regionCode);
      yield mysql.query('insert into mh_business_region(parent_id,region_id,region_name,region_type,city_code,center_location) select ?,?,?,?,?,? from dual' + sql, [cityRegionCode, regionCode, regionName, region_type, cityCode, regionLocation]);

      //level3 district
      let district = cityDistinct[i].districts;
      if (district.length == 0) {
        continue;
      }
      let areaParentCode = regionCode;
      for (let j in district) {
        let regionType = district[j].level;
        if (regionType == 'district') {
          regionCode = district[j].adcode;
          regionName = district[j].name;
          regionLocation = district[j].center;
          cityCode = district[j].citycode;
          region_type = 3;
          let sql = ' where not exists(select 1 from mh_business_region where region_id =\'' + regionCode + '\' and region_name=\'' + regionName + '\' and parent_id=\'' + areaParentCode + '\' and region_type=' + region_type + ')';
          console.log('区 ' + regionName + '  ' + regionCode);
          yield mysql.query('insert into mh_business_region(parent_id,region_id,region_name,region_type,city_code,center_location) select ?,?,?,?,?,? from dual' + sql, [areaParentCode, regionCode, regionName, region_type, cityCode, regionLocation]);

          //level4 business area
          let businessDistrict = district[j].districts;
          if (businessDistrict.length == 0) {
            continue;
          }
          let busiParentCode = regionCode;
          for (let k in businessDistrict) {
            regionCode = businessDistrict[k].areacode;
            regionName = businessDistrict[k].name;
            regionLocation = businessDistrict[k].center;
            cityCode = businessDistrict[k].citycode;
            region_type = 4;
            let sql = ' where not exists(select 1 from mh_business_region where region_id =\'' + regionCode + '\' and region_name=\'' + regionName + '\' and parent_id=\'' + busiParentCode + '\' and region_type=' + region_type + ')';
            console.log('商圈 ' + regionName + '  ' + regionCode);
            yield mysql.query('insert into mh_business_region(parent_id,region_id,region_name,region_type,city_code,center_location) select ?,?,?,?,?,? from dual' + sql, [busiParentCode, regionCode, regionName, region_type, cityCode, regionLocation]);
          }
        }
        else if (regionType == 'biz_area') {
          //level4 business area
          let businessDistrict = district;
          regionCode = district[j].areacode;
          regionName = district[j].name;
          regionLocation = district[j].center;
          cityCode = district[j].citycode;
          region_type = 4;
          let sql = ' where not exists(select 1 from mh_business_region where region_id =\'' + regionCode + '\' and region_name=\'' + regionName + '\' and parent_id=\'' + areaParentCode + '\' and region_type=' + region_type + ')';
          console.log('商圈 ' + regionName + '  ' + regionCode);
          yield mysql.query('insert into mh_business_region(parent_id,region_id,region_name,region_type,city_code,center_location) select ?,?,?,?,?,? from dual' + sql, [areaParentCode, regionCode, regionName, region_type, cityCode, regionLocation]);
        }
      }
    }
  }
};

exports.getWatsonsGeo2 = function*(Env) {
  var loginStatus = yield F.isLogin(Env);
  manLog(loginStatus, 999, '生成屈臣氏geo表', Env['ip'], Env['I']);
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid, [1, 2]))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var fields = Env.I;
  var act = fields.act;
  var homeURL = 'http://www.watsons.com.cn/storelocator';
  var home = '';
  if (act == 1) {
    let options = {
      url: homeURL,
      headers: {'User-Agent': 'request'},
      method: 'GET',
      timeout: 5000
    };

    var arr;
    // 取省
    //<li class="dotTop" onclick="getAreaListByCity2('8796650181083');">福建省</li>
    let patt = /getCityListByPronvince\(\'(\d+)\'\)\;\"\>([^<]*)\</mg;
    var addr1 = {};
    home = {};
    for (let j = 0; j < 10; j++) {
      try {
        home = yield request(options);
        break;
      }
      catch (err) {
        console.log(err);
      }
    }
    let body = home.body || '';
    while ((arr = patt.exec(body)) != null) {
      let sql = ' where not exists(select 1 from mh_watsons where wid =\'' + arr[1] + '\' and name=\'' + arr[2] + '\' and pid=0)';
      console.log('省 ' + arr[1] + '  ' + arr[2]);
      yield mysql.query('insert into mh_watsons(pid,wid,name,lv) select 0,?,?,1 from dual' + sql, [arr[1], arr[2]]);
      addr1[arr[1]] = arr[2];
    }

    //取市
    //{'uid':'8796651491803','name':'芜湖市'}
    patt = /\'uid\'\:\'(\d+)\'\,\'name\'\:\'([^']+)\'/mg;
    var addr2 = {};
    for (let i in addr1) {
      options.url = 'http://www.watsons.com.cn/view/InfinityStoreLocatorComponentController/getAreaListByCity?uid=' + i;
      home = {};
      for (let j = 0; j < 10; j++) {
        try {
          home = yield request(options);
          break;
        }
        catch (err) {
          console.log(err);
        }
      }
      body = home.body || '';
      while ((arr = patt.exec(body)) != null) {
        let sql = ' where not exists(select 1 from mh_watsons where wid =\'' + arr[1] + '\' and name=\'' + arr[2] + '\' and pid=\'' + i + '\')';
        console.log('市 ' + arr[1] + '  ' + arr[2]);
        yield mysql.query('insert into mh_watsons(pid,wid,name,lv) select ?,?,?,2 from dual' + sql, [i, arr[1], arr[2]]);
        addr2[arr[1]] = arr[2];
      }
    }


    //取区
    //{'uid':'8796651491803','name':'芜湖市'}
    patt = /\'uid\'\:\'(\d+)\'\,\'name\'\:\'([^']+)\'/mg;
    var addr3 = {};
    for (let i in addr2) {
      options.url = 'http://www.watsons.com.cn/view/InfinityStoreLocatorComponentController/getAreaListByCity?uid=' + i;
      home = {};
      for (let j = 0; j < 10; j++) {
        try {
          home = yield request(options);
          break;
        }
        catch (err) {
          console.log(err);
        }
      }
      body = home.body || '';
      while ((arr = patt.exec(body)) != null) {
        let sql = ' where not exists(select 1 from mh_watsons where wid =\'' + arr[1] + '\' and name=\'' + arr[2] + '\' and pid=\'' + i + '\')';
        console.log('区 ' + arr[1] + '  ' + arr[2]);
        yield mysql.query('insert into mh_watsons(pid,wid,name,lv) select ?,?,?,3 from dual'
          + sql, [i, arr[1], arr[2]]);
        addr3[arr[1]] = arr[2];
      }
    }

    // 取具体店面
    // storeInfoJson=storeInfoJson+"{'lng':'117.3660217','lat':'32.92530326','name':'安徽蚌埠蚌山万达广场店','address':'蚌山区东海大道4399号万达广场2','phone':''},"
    patt = /\'lng\'\:\'(\d+\.\d+)\'\,\'lat\'\:\'(\d+\.\d+)\'\,\'name\'\:\'([^']+)\'\,\'address\'\:\'([^']+)\'\,'/mg;
    var addr4 = {};
    for (let i in addr3) {
      options.url = 'http://www.watsons.com.cn/view/InfinityStoreLocatorComponentController/searchMapStoreIndfo?uid=' + i + '&all=Y';
      home = {};
      for (let j = 0; j < 10; j++) {
        try {
          home = yield request(options);
          break;
        }
        catch (err) {
          console.log(err);
        }
      }
      body = home.body || '';

      while ((arr = patt.exec(body)) != null) {
        addr4[i] = {
          lng: arr[1], lat: arr[2], name: arr[3], address: arr[4]
        };
        let sql = ' where not exists(select 1 from mh_watsons where name=\'' + addr4[i].name + '\' and pid=\'' + i + '\' and shopaddress=\'' + addr4[i].address + '\')';
        console.log('街 ' + arr[1] + '  ' + arr[2] + '  ' + arr[3] + '  ' + arr[4]);
        let flag = yield mysql.query('insert into mh_watsons(pid,name,lv,lng,lat,shopaddress) ' +
          'select ?,?,4,?,?,? from dual' + sql, [i, addr4[i].name, addr4[i].lng, addr4[i].lat, addr4[i].address]);
        if (flag.affectedRows > 0) {
          options.url = C.amap.poi_rest_convert_url + '?locations=' + addr4[i].lng + ',' + addr4[i].lat + '&coordsys=baidu&output=json&key=' + C.amap.api_rest_key;
          home = {};
          for (let j = 0; j < 10; j++) {
            try {
              home = yield request(options);
              break;
            }
            catch (err) {
              console.log(err);
            }
          }
          let body2 = home.body || '{}';
          var amapLocation = JSON.parse(body2);
          if (amapLocation['status'] == 1 && amapLocation['info'] == 'ok') {
            yield mysql.query('update mh_watsons set amap_lng=\'' + amapLocation.locations.split(',')[0] + '\',amap_lat=\'' + amapLocation.locations.split(',')[1] +
              '\' where name=\'' + addr4[i].name + '\' and pid=\'' + i + '\' and shopaddress=\'' + addr4[i].address + '\'')
          }
        }
      }
    }
  }
  return F.returnMsg(200, '', 3, addr4)
};
/*@API48 增加瓷肌百科页面
act:1-新增页面；2-修改页面；3-根据页面id获取详细内容；4-获取全部页面；5-根据type以及相关的id获取页面详细
* */
exports.ciJiWiki = function* (Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  let act=fields.act;
  let type=fields.type;
  let idFromType=fields.idFromType;
  let status=fields.status;
  let page = fields.page || 1;
  let pageSize = fields.pagesize != undefined ? parseInt(fields.pagesize) : C.threadlist.pageSize;

  let obj_page={};

  manLog(loginStatus, 48, 'ciJiWiki', Env['ip'], Env['I']);
  if (!(loginStatus.status == true)) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  let json_data=fields.data_json;

  if (act == 1 || (act == 2 && json_data != undefined)) {
    if(!F.isJson(json_data)){
      return F.returnMsg(400, '请传入有效的json数据', 1);
    }
    json_data=JSON.parse(json_data);
    if(json_data.pageName==undefined || _.isEmpty(json_data.pageName)){
      return F.returnMsg(400, '请传入页面名称字段pageName', 1);
    }

    for (let i in json_data.items) {
      let item =json_data.items[i];
      let param=item.param;
      let data=item.data;
      let type=param.type;
      if(!_.v.isIn(type,[16,20,21])){
        return F.returnMsg(400, '第'+i+'项的类型无效，只支持[16,20,21]', 1);
      }
      let style = param.style;

      if (type != 16) {
        let title = data.title;
        let desc = data.desc;

        if (title == undefined || _.isEmpty(title)) {
          return F.returnMsg(400, '第' + i + '项的标题不能为空', 1);
        }
        if (desc == undefined || desc == '') {
          return F.returnMsg(400, '第' + i + '项的描述不能为空', 1);
        }
        if (type == 21 && (!_.v.isFloat(desc))) {
          return F.returnMsg(400, '第' + i + '项的type为21,描述必须为数值型', 1);
        }
      }
      if (style == undefined || !_.v.isInt(style)) {
        return F.returnMsg(400, '第' + i + '项的样式参数无效', 1);
      }
    }
    obj_page = {act:1,pageName: json_data.pageName, content:json_data, status: 1, type: type, idFromType: idFromType};
  }


  let wikiSection= require('../model/mWikiPage');
  if(act==1){//新增瓷肌百科页面
    return yield wikiSection.addPage(obj_page);
  }else if(act==2){//修改单个瓷肌百科页面
    let id=fields.id;
    if(!_.v.isInt(id)){
      return F.returnMsg(400, 'id只能传入数字', 1);
    }
    for (let p in obj_page) {
      if (obj_page[p] == undefined) {
        delete obj_page[p];
      }else if(p=='type'){
        if(!_.v.isIn(obj_page[p],[1,2])){
          return F.returnMsg(400, 'type暂时支持1,2', 1);
        }
      }else if(p=='idFromType'){
        if(!_.v.isInt(obj_page[p])){
          return F.returnMsg(400, 'idFromType只能传入数字', 1);
        }
      }
    }
    obj_page.id=parseInt(id);
    return yield wikiSection.updatePage(obj_page);
  }else if(act==3){//获取单个瓷肌百科页面数据
    let idFromType=fields.idFromType;
    if(!_.v.isInt(idFromType)){
      return F.returnMsg(400, 'idFromType只能传入数字', 1);
    }
    idFromType=parseInt(idFromType);
    let ret=yield wikiSection.getPageByTypeNId(type,idFromType);
    if(ret.status==300){
      return F.returnMsg(300, '系统找不到对应的页面', 1);
    }else{
      return F.returnMsg(200, '成功', 1,ret);
    }
  }
  else if(act==4){//获取全部瓷肌百科页面标题
    if(!_.v.isInt(type)){
      return F.returnMsg(400, 'type字段为必须参数', 1);
    }else{
      type=parseInt(type);
    }
    let obj_param={act:1,page:page,pageSize:pageSize,type:type};
    if(status!=undefined){
      if(!_.v.isIn(status,[0,1])){
        return F.returnMsg(400, 'status字段只能传入0或1', 1);
      }
    }
    return yield wikiSection.getPageList(obj_param);
  }else if(act==5){//根据type和响应的id获取页面
    if(status!=undefined){
      if(!_.v.isIn(status,[0,1])){
        return F.returnMsg(400, 'status字段只能传入0或1', 1);
      }
    }
    let page=yield wikiSection.getPageByTypeNId(type,idFromType);
    return F.returnMsg(200, '成功', 1,page);
  }
};